简体   繁体   English

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

[英]my project login doesnt work in asp.net core

I am new to programming, I don't get any errors in my program but my login doesn't work and when I enter the password and username and click the button, it doesn't go to the admin page - it actually doesn't go anywhere and returns the login page (itself).我是编程新手,我的程序没有任何错误,但我的登录不起作用,当我输入密码和用户名并单击按钮时,它不会 go 到管理页面 - 它实际上没有t go 任何地方并返回登录页面(本身)。

My admin action method has [Authorize] attribute and everything is ok in the database I think, and data insert with seed data.我的管理操作方法具有[Authorize]属性,我认为数据库中的一切正常,并且数据插入种子数据。 Please help.请帮忙。

startup.cs启动.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 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<Claim>
        {
            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登录存储库.cs

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

ILoginRepository.cs ILoginRepository.cs

string IsExistUser(string username, string password);

login.cshtml登录.cshtml

@model DataLayer.Admin

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

<div class="container">

    <form  onsubmit="return true" name="loginform" method="post" class="box box1 band form pb-3 pt-3  col-lg-12  col-md-12 col-sm-12 col-12">
        <div class="row">
            <div class="form-group floating-label-group col-12">
                <i class="zmdi zmdi-account userdarkmode userdarkmode1"></i>
                <input asp-for="UserName" name="UserName" class="form-control UserName UserName1" required title="enter your username" />
                <label asp-for="UserName" class="control-label floating-label-username floating-label-username1">username:</label>
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
        </div>

        <div class="row">
            <div class="form-group floating-label-group col-12">
                <i class="zmdi zmdi-key keydarkmode keydarkmode1"></i>
                <input asp-for="Password" name="Password" class="form-control Password Password1" autocomplete="off" required title="entere your password" />
                <label asp-for="Password" class="control-label floating-label-password floating-label-password1">password:</label>
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                <input asp-for="RememberMe" class="form-check-input form-control rememberdarkmode rememberdarkmode1 col-1" name="RememberMe" />
                <label asp-for="RememberMe" class="form-check-label rememberdarkmode rememberdarkmode1 opt col-11"></label>
            </div>
        </div>
        <div class="form-group col-12">
            <input type="submit" value="enter" asp-action="Admin" asp-controller="Home" class="btn btn-outline-success form-control col-6" />
        </div>

        <div>
            <a asp-action="Index" asp-controller="Home" class="text text1 col-6 text-secondary">go to form</a>
        </div>
    </form>
</div>



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

model.cs 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();
        }

And my model validation doesn't work either ( asp-validation-for in inputs) - I don't know why.而且我的 model 验证也不起作用(输入中asp-validation-for ) - 我不知道为什么。

Where do you have your function call out in the button parameters?你在哪里有你的 function 在按钮参数中调用?

Use https://getbootstrap.com/docs/5.0/components/buttons/ -> use button , not input type="submit" .使用https://getbootstrap.com/docs/5.0/components/buttons/ -> 使用button ,而不是input type="submit" https://stackoverflow.com/a/33663114/11394571 https://stackoverflow.com/a/33663114/11394571

You need a https://www.educba.com/button-in-asp-net/ :你需要一个https://www.educba.com/button-in-asp-net/

OnClick="Login"

Look at this part of your form:查看表单的这一部分:

<div class="form-group col-12">
<input type="submit" value="enter" asp-action="Admin" asp-controller="Home" class="btn btn-outline-success form-control col-6" />
</div>

You are posting your request to the Admin action in Home Controller.您正在将您的请求发布到主页 Controller 中的管理员操作。 You are not sending it to your AccountController.您没有将其发送到您的 AccountController。 Change it to asp-action="Login" asp-controller="Account".将其更改为 asp-action="Login" asp-controller="Account"。

About the model validation you should have this in your HttpPost Login:关于 model 验证,您应该在 HttpPost 登录中包含以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM