RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

问题[asp.net-mvc]

Martin Hope
Monoclocker
Asked: 2023-12-04 20:41:53 +0000 UTC

ASP.NET MVC 中的模型逻辑

  • 5

出现了一个建筑问题。我正在使用 ASP.NET MVC 编写 Web API。ORM——实体框架。在模型中创建方法来处理它们是否正确,还是只保留其中的字段和属性更好?如果您正确创建方法,那么处理错误/验证/返回状态代码的最佳方法是什么?

asp.net-mvc
  • 1 个回答
  • 37 Views
Martin Hope
user511657
Asked: 2022-07-23 15:41:55 +0000 UTC

服务器响应错误:500 ASP.NET Core

  • 0

我想用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;

}
asp.net-mvc asp.net
  • 1 个回答
  • 49 Views
Martin Hope
User
Asked: 2022-09-08 15:26:55 +0000 UTC

用新的替换旧的控制器链接[关闭]

  • 0
关闭。这个问题不可能给出客观的答案。目前不接受回复。

想改进这个问题? 重新构建问题,以便可以根据事实和引用来回答。

2 个月前关闭。

改进问题

我正在制作我的宠物项目以熟悉 asp.net core mvc。最初,有一个控制器User负责与用户一起工作(注册、授权、密码更改和退出),还有一个方法Login负责登录。有一次,我想将控制器的名称从 to 更改为User,Account将方法的名称从Loginto更改为Sigin,并且尽可能地替换链接。基本上我有两个问题:

  1. 如果需要更改控制器或方法的名称怎么办,然后在整个项目中查找旧名称并更改为新名称(Startup设置时的视图、代码、类CookieAuthenticationOptions)
  2. 如果项目已经发展到 >=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>
c# asp.net-mvc
  • 1 个回答
  • 63 Views
Martin Hope
Ерлан Сакан
Asked: 2022-09-03 22:24:06 +0000 UTC

InvalidOperationException:尝试激活时无法解析服务类型

  • 0

这是错误的全文(编译时没有错误。我无法访问此页面):

在此处输入图像描述

你好。我的购物车有问题。我不知道如何解决它。请帮忙。

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();
        }
    }
}
c# asp.net-mvc
  • 1 个回答
  • 59 Views
Martin Hope
Dmitro Nychyporuk
Asked: 2022-08-11 23:02:39 +0000 UTC

使用Where检查多个值C#

  • 0

我有一个值列表

 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。

asp.net-mvc entity-framework
  • 1 个回答
  • 17 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5