简体   繁体   English

如何使用 ASP.NET Core 3.1 实现自定义登录?

[英]How to implement custom LogIn with ASP.NET Core 3.1?

I have a testing database on my local server.我的本地服务器上有一个测试数据库。 In the database, I have a table called "Korisnici" (eng. Users).在数据库中,我有一个名为“Korisnici”(英语用户)的表。 Using EntityFrameworkCore I generated classes from a database, and here is generated "Korisnici" class:使用 EntityFrameworkCore 我从数据库生成类,这里生成“Korisnici”class:

public partial class Korisnici
{
    public Korisnici()
    {
        BankovniRacuni = new HashSet<BankovniRacuni>();
        Dokumenti = new HashSet<Dokumenti>();
        ObracuniZarada = new HashSet<ObracuniZarada>();
        Poslodavci = new HashSet<Poslodavci>();
        PrihodiPoslodavca = new HashSet<PrihodiPoslodavca>();
        RashodiPoslodavca = new HashSet<RashodiPoslodavca>();
        Takse = new HashSet<Takse>();
        Zaposleni = new HashSet<Zaposleni>();
    }

    public int Id { get; set; }
    public string Ime { get; set; }
    public string Prezime { get; set; }
    [Required]
    [Display(Name = "Korisnicko ime")]
    public string KorisnickoIme { get; set; }
    public string Email { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Lozinka")]
    public string Lozinka { get; set; }
    public int? TipKorisnika { get; set; }

    public virtual TipoviKorisnika TipKorisnikaNavigation { get; set; }
    public virtual ICollection<BankovniRacuni> BankovniRacuni { get; set; }
    public virtual ICollection<Dokumenti> Dokumenti { get; set; }
    public virtual ICollection<ObracuniZarada> ObracuniZarada { get; set; }
    public virtual ICollection<Poslodavci> Poslodavci { get; set; }
    public virtual ICollection<PrihodiPoslodavca> PrihodiPoslodavca { get; set; }
    public virtual ICollection<RashodiPoslodavca> RashodiPoslodavca { get; set; }
    public virtual ICollection<Takse> Takse { get; set; }
    public virtual ICollection<Zaposleni> Zaposleni { get; set; }
}

This class is used as a model for one View called "Index.cshtml":此 class 用作名为“Index.cshtml”的一个视图的 model:

@model Korisnici
<img src="/Content/images/LogoFinal.png" />
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account"))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.KorisnickoIme, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.KorisnickoIme, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.KorisnickoIme, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Lozinka, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Lozinka, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Lozinka, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Uloguj se" class="btn btn-primary" />
                    </div>
                </div>
            }
        </section>
    </div>
</div>

When I click on a submit button, Login action from Controler "AccountControler" is called.当我单击提交按钮时,会调用来自控制器“AccountControler”的登录操作。

public class AccountController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Login(LoginViewModel model)
    {
        // Acces database and search for account
        var dbContext = new AdministracijaZingDevDBContext();
        var korisnik = dbContext.Korisnici
            .Where(k => k.KorisnickoIme == model.KorisnickoIme)
            .Where(k => k.Lozinka == model.Lozinka)
            .FirstOrDefault();

        if (korisnik != null)
        {
            HttpContext.Session.SetString("UserName" , model.KorisnickoIme);
            

            return RedirectToAction("Index", "Main");
        }

        return RedirectToAction("Index", "Home");
    }
    
}

I have inserted testing data in a database with one record of the Korisnici table.我已将测试数据插入数据库中,其中包含 Korisnici 表的一条记录。 When I enter correct data into the LogIn form, nothing happens (the user didn't pass login).当我在登录表单中输入正确的数据时,什么也没有发生(用户没有通过登录)。

just to check, you created migration files and updated the db and so on?只是为了检查,您创建了迁移文件并更新了数据库等等?

(This should be in a comment, but I lack the reputation) (这应该在评论中,但我缺乏声誉)

also you shouldn't create a new context, but inject it into the constructor of your account controller ( or beter still... you should inject a repository or better use a unit of work-design and CQRS-design)你也不应该创建一个新的上下文,而是将它注入到你的帐户 controller 的构造函数中(或者更好......你应该注入一个存储库或者更好地使用一个工作设计单元和 CQRS 设计)

Take care and good luck.保重,祝你好运。

so you type ctor tab tab所以你输入 ctor tab tab

which would give you这会给你

public AccountController(){}

and than you add a parameter in the AccountController-function like并且比您在 AccountController-function 中添加一个参数,例如

public AccountController(MyContext context){} 

right click => quick actions and refactoring => create and assign property MyContext右键单击 => 快速操作和重构 => 创建和分配属性 MyContext

but you should create at least a repositorypattern and inject something like IKorisniciRepository.但是您应该至少创建一个存储库模式并注入 IKorisniciRepository 之类的东西。

It would be easier if you placed your repo on gitHub so I can test before writing.如果您将存储库放在 gitHub 上会更容易,这样我就可以在编写之前进行测试。

Try尝试

 public class AccountController : Controller
{
    private readonly AdministracijaZingDevDBContext Context {get;}

    public AccountController (AdministracijaZingDevDBContext context) {Context = context;}

    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Login(LoginViewModel model)
    {
        // Access database and search for account
       
        var korisnik = Context.Korisnici
            .Where(k => k.KorisnickoIme == model.KorisnickoIme)
            .Where(k => k.Lozinka == model.Lozinka)
            .FirstOrDefault();

    if (korisnik != null)
    {
        HttpContext.Session.SetString("UserName" , model.KorisnickoIme);
        

        return RedirectToAction("Index", "Main");
    }

    return RedirectToAction("Index", "Home");
}

} }

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

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