出现了一个建筑问题。我正在使用 ASP.NET MVC 编写 Web API。ORM——实体框架。在模型中创建方法来处理它们是否正确,还是只保留其中的字段和属性更好?如果您正确创建方法,那么处理错误/验证/返回状态代码的最佳方法是什么?
user511657
Asked:
2022-07-23 15:41:55 +0800 CST
我想用angular和asp做一个服装店,但是我遇到了将数据发送到数据库的困难。有一个用于注册和授权的模块化表格。首先,我决定实现注册表单,但是发送数据时出错:
我是新手,所以我附上了代码,因为我不知道错误的问题是什么。
用户.ts:
export class Users{
id? = "";
phone = "";
email = "";
fio = "";
address ="";
password = "";
}
用户服务.ts:
@Injectable({
providedIn: 'root'
})
export class UserServiceService {
private url = "User";
constructor(private http: HttpClient) {
}
@Input() public createUser(users: Users): Observable<Users> {
return this.http.post<Users>(
`${environment.apiUrl}/${this.url}`,
users
);
导航菜单.ts:
export class NavMenuComponent {
user:Users =new Users;
@Output() userUpdated = new EventEmitter<Users>();
constructor(private superHeroService: UserServiceService) {}
createnewUser(users: Users) {
this.superHeroService
.createUser(users)
.subscribe((users: Users) => this.userUpdated.emit(users));
}
}
从输入中读取变量:
<div class="modal-body">
<input [(ngModel)]="user.email" class="form-control">
<input [(ngModel)]="user.phone" class="form-control">
<input [(ngModel)]="user.address" class="form-control">
<input [(ngModel)]="user.fio" class="form-control">
<input type="password" [(ngModel)]="user.password" class="form-control"> :
<input type="password" class="form-control">
</div>
后端:
用户控制器.cs:
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
private readonly DataContext _context;
public UserController(DataContext context)
{
_context = context;
}
[HttpPost]
public async Task<IActionResult> CreateUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return Ok(await _context.Users.ToListAsync());
}
}
数据上下文.cs:
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<User> Users => Set<User>();
}
User.cs:公共类用户
{
public string? Id = string.Empty;
public string Phone = string.Empty;
public string Email = string.Empty;
public string FIO = string.Empty;
public string Password = string.Empty;
}
User
Asked:
2022-09-08 15:26:55 +0800 CST
我正在制作我的宠物项目以熟悉 asp.net core mvc。最初,有一个控制器User
负责与用户一起工作(注册、授权、密码更改和退出),还有一个方法Login
负责登录。有一次,我想将控制器的名称从 to 更改为User
,Account
将方法的名称从Login
to更改为Sigin
,并且尽可能地替换链接。基本上我有两个问题:
- 如果需要更改控制器或方法的名称怎么办,然后在整个项目中查找旧名称并更改为新名称(
Startup
设置时的视图、代码、类CookieAuthenticationOptions
) - 如果项目已经发展到 >=10 个控制器并且在每个控制器中 >=5 个方法
HttpGet
,并且您无法记住所有这些控制器,您需要调用其中一个,该怎么办。
这是我解决问题的方法
public static class LinksConstants
{
public static class Account
{
public const String Controller = "Account";
public const String SignUpActionName = "SignUp";
public const String SignInActionName = "SignIn";
public const String ChangePasswordActionName = "ChangePassword";
public const String SignOutActionName = "SignOut";
public static readonly String SignUpLink;
public static readonly String SignInLink;
public static readonly String ChangePasswordLink;
public static readonly String SignOutLink;
static Account()
{
String mask = "/{0}/{1}";
SignUpLink = String.Format(mask , Controller , SignUpActionName);
SignInLink = String.Format(mask , Controller , SignInActionName);
ChangePasswordLink = String.Format(mask , Controller , ChangePasswordActionName);
SignOutLink = String.Format(mask , Controller , SignOutActionName);
}
}
}
public class AccountController : Controller
{
[HttpGet, AllowAnonymous, ActionName(LinksConstants.Account.SignInActionName)]
public async Task<IActionResult> SignInView([FromServices] SignInManager signInManager ,
[FromQuery] String returnUrl = null)
{
//do work
}
}
<div class="clearfix">
<a class="float-right" asp-route-returnUrl="@Model.ReturnUrl" asp-controller=@LinksConstants.Account.Controller asp-action=@LinksConstants.Account.SignUpActionName>Create account</a>
</div>
您如何在实际项目中解决此类问题?
模型
public sealed class SignInViewModel
{
#region Fields
public static readonly SignInViewModel Empty;
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email")]
public String Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[Remote(action: LinksConstants.RemoteValidation.ValidationPasswordActionName , controller: LinksConstants.RemoteValidation.Controller)]
public String Password { get; set; }
[ScaffoldColumn(false), ValidateNever]
public String ReturnUrl { get; set; }
#endregion Fields
static SignInViewModel()
{
Empty = new SignInViewModel()
{
ReturnUrl = "/"
};
}
public async Task ValidationOnServer(ModelStateDictionary modelState , UserManager userManager)
{
UserEntity user = await userManager.FindByEmailAsync(Email);
if (user is null || !await userManager.CheckPasswordAsync(user , Password))
{
String message = "Invalid email or password";
modelState.TryAddModelError(nameof(Email) , message);
modelState.TryAddModelError(nameof(Password) , message);
}
}
}
看法
@using WebContacts.Models.Account;
@model SignInViewModel
@section Scripts
{
<partial name="_ValidationScriptsPartial" />
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="account" method="post" asp-route-returnUrl="@Model.ReturnUrl">
<div class="container py-0 ">
<div class="row d-flex justify-content-center align-items-center ">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-5 text-center">
<h3 class="mb-5">Sign in</h3>
<div class="form-outline mb-4">
<input class="form-control form-control-lg" asp-for="@Model.Email" />
<label class="form-label" asp-for="@Model.Email"></label>
<span class="text-danger" asp-validation-for="@Model.Email"></span>
</div>
<div class="form-outline mb-4">
<input class="form-control form-control-lg" asp-for="@Model.Password" />
<label class="form-label" asp-for="@Model.Password"></label>
<span class="text-danger" asp-validation-for="@Model.Password"></span>
</div>
<button class="btn btn-primary btn-lg btn-block" type="submit">Login</button>
<div class="clearfix">
<a class="float-right" asp-route-returnUrl="@Model.ReturnUrl" asp-controller=@LinksConstants.Account.Controller asp-action=@LinksConstants.Account.SignUpActionName>Create account</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Ерлан Сакан
Asked:
2022-09-03 22:24:06 +0800 CST
这是错误的全文(编译时没有错误。我无法访问此页面):
你好。我的购物车有问题。我不知道如何解决它。请帮忙。
using Microsoft.EntityFrameworkCore;
using WebApplication1;
using WebApplication1.Interface;
using WebApplication1.mocks;
using WebApplication1.Models;
using WebApplication1.Repository;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("dbsettings.json").Build();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDBContent>(x => x.UseSqlServer(connectionString));
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddTransient<IAllTicket, TicketRepository>();
builder.Services.AddTransient<ITicketCategory, CategoryRepository>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddScoped(sp => ShopCart.GetCart(sp));
builder.Services.AddMvc();
builder.Services.AddMemoryCache();
builder.Services.AddSession();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
using (var scope = app.Services.CreateScope())
{
AppDBContent content = scope.ServiceProvider.GetRequiredService<AppDBContent>();
DBObject.Initial(content);
}
app.Run();
控制器本身的代码
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using WebApplication1.Repository;
using WebApplication1.ViewModels;
namespace WebApplication1.Controllers
{
public class ShopCartController : Controller
{
private readonly TicketRepository _gameRep;
private readonly ShopCart _shopCart;
public ShopCartController(TicketRepository gameRep, ShopCart gameCart)
{
_gameRep = gameRep;
_shopCart = gameCart;
}
public ViewResult Index()
{
var items = _shopCart.getShopItems();
_shopCart.listShopItems = items;
var obj = new ShopCartViewModel
{
shopCart = _shopCart
};
return View(obj);
}
public RedirectToActionResult addtoCart(int id)
{
var item = _gameRep.Tickets.FirstOrDefault(i => i.Id == id);
if(item != null)
{
_shopCart.AddtoCart(item);
}
return RedirectToAction("Index");
}
}
}
模型代码
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class ShopCart
{
private readonly AppDBContent appDBContent;
public ShopCart(AppDBContent appDBContent)
{
this.appDBContent = appDBContent;
}
public string ShopCartId { get; set; }
public List<ShopCartItem> listShopItems { get; set; }
public static ShopCart GetCart(IServiceProvider services)
{
ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
var context = services.GetService<AppDBContent>();
string shopCartid = session.GetString("Cartid") ?? Guid.NewGuid().ToString();
session.SetString("Cartid", shopCartid);
return new ShopCart(context) { ShopCartId = shopCartid };
}
public void AddtoCart(Ticket ticket)
{
appDBContent.ShopCartItem.Add(new ShopCartItem
{
ShopCartId = ShopCartId,
ticket = ticket,
price = ticket.Price,
});
appDBContent.SaveChanges();
}
public List<ShopCartItem> getShopItems()
{
return appDBContent.ShopCartItem.Where(c => c.ShopCartId == ShopCartId).Include(s => s.ticket).ToList();
}
}
}
Dmitro Nychyporuk
Asked:
2022-08-11 23:02:39 +0800 CST
我有一个值列表
var CurPareID = _context.PareSubgroups.Where(p => p.Subgroup_Id == StudentSubgrId).Select(p => p.Pare_Id).ToList();
这是一个请求
ViewBag.monday_item = _context.Schedules
.Include(p => p.PairTime)
.Include(p => p.Semester)
.Include(p => p.Subject)
.Include(p => p.Teacher)
.Where(p => p.Teacher_Id ==TeacherId);
我想使用 Where 来检查上下文中是否有列表中的值,但它只针对一个值。如何检查我的上下文是否包含所有这些值。是否有任何类似于 C# 的 Sql 中的 ON。