我的项目登录在 asp.net 核心中不起作用

分享于2022年07月17日 asp.net asp.net-core asp.net-identity c# identity 问答
【问题标题】:我的项目登录在 asp.net 核心中不起作用(my project login doesnt work in asp.net core)
【发布时间】:2022-01-27 06:07:08
【问题描述】:

我是编程新手,我的程序没有任何错误,但我的登录不起作用,当我输入密码和用户名并单击按钮时,它不会进入管理页面 - 它实际上并没有去任何地方并返回登录页面(本身)。

我的管理操作方法具有 [Authorize] 属性,并且我认为数据库中的一切正常,并且数据插入带有种子数据。请帮忙。

startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStatusCodePagesWithRedirects("/Home/Error");
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
}

AccountController.cs

public IActionResult Login()
{
    return View();
}

[HttpPost]
public IActionResult Login(Admin login, FormCollection form)
{
    if (ModelState.IsValid)
    {
        var user = loginRepository.IsExistUser(login.UserName, login.Password);

        if (user != "")
        {
            return Redirect("/Home/Admin");
        }
        else
        {
            ModelState.AddModelError("UserName", "there is no user");
        }
    }

    var claims = new List
        {
            new Claim(ClaimTypes.NameIdentifier,login.LoginID.ToString()),
            new Claim(ClaimTypes.Name,login.UserName),
            new Claim(ClaimTypes.Name,login.Password),
        };

    var Identity = new ClaimsIdentity(claims, `enter code here`CookieAuthenticationDefaults.AuthenticationScheme);
    var principal = new ClaimsPrincipal(Identity);

    var properties = new AuthenticationProperties
        {
            IsPersistent = login.RememberMe
        };

    HttpContext.SignInAsync(principal, properties);

    //********recaptcha * ********
    string urlToPost = "https://www.google.com/recaptcha/api/siteverify";
    string secretKey = "";
    string gRecaptchaResponse = form["g-recaptcha-response"];

    var postData = "secret=" + secretKey + "&response=" + gRecaptchaResponse;

    // send post data
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToPost);
    request.Method = "POST";
    request.ContentLength = postData.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(postData);
    }

    // receive the response now
    string result = string.Empty;

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }
    }

    ViewBag.IsSuccess = false;

    return View("login");
}

public IActionResult Lougout()
{
    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Redirect("/Account/Login");
}

LoginRepository.cs

public string IsExistUser(string username, string password)
{
    return db.Admin.SingleOrDefault(u => u.UserName == username && u.Password == password).ToString();
}

ILoginRepository.cs

string IsExistUser(string username, string password);

login.cshtml

@model DataLayer.Admin

@{
    ViewData["LoginTitle"] = "sign in";
    Layout = "/Views/Shared/_LoginLayout.cshtml";
}

@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

model.cs


using System.ComponentModel.DataAnnotations;

namespace DataLayer
{
    public class Admin
    {
        [Key]
        public int LoginID { get; set; }

        [Display(Name = "username")]
        [Required(ErrorMessage = "please enter your username")]
        [MaxLength(20)]
        public string UserName { get; set; }


        [Display(Name = "password")]
        [Required(ErrorMessage = "please enter your password")]
        [MaxLength(20)]
        [DataType(DataType.Password)]
        public string Password { get; set; }


        [Display(Name = "remember me")]
        public bool RememberMe { get; set; }
    }
}

HomeController

        [Authorize]
        public IActionResult Admin()
        {
            return View();
        }

而且我的模型验证也不起作用(输入中的 asp-validation-for ) - 我不知道为什么。

  • And my model validation doesn't work either (asp-validation-for in inputs) ,您在页面加载时是否正确加载了 _ValidationScriptsPartial 中的 jquery.validate.min.js jquery.validate.unobtrusive.min.js
  • 我的 _ValidationScriptsPartial 中有,但验证无法再次工作,客户端验证正在工作,但服务器端 (asp-validation-for) 无法正常工作

【解决方案1】:

查看表单的这一部分:

您正在将您的请求发布到 Home Controller 中的 Admin 操作。您没有将其发送到您的 AccountController。将其更改为 asp-action="Login" asp-controller="Account" 。

关于模型验证,您应该在 HttpPost 登录中包含以下内容:

if(!ModelState.IsValid)
{
return View(login);
}

  • 我在 HttpPost 登录中有此代码,但是当我将其更改为管理员操作帐户控制器时,我有 500 个状态代码(此页面无法正常工作,本地主机当前无法处理此请求)错误.
  • 您能否在 AccountController 中发布管理操作,因为从上面的 sn-p 我看不到它。你在使用区域吗?
  • 您是否尝试将表单提交更改为 asp-action="Login" asp-controller="Account",正如我所指出的那样?
  • 不,我不只是为管理员制作控制器、视图和模型
  • 是的,我尝试过,但没有成功