2

我正在创建 ASP.NET MVC Web 应用程序。我有数据模型用户:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Knihovna.Models
{
    public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public List<Book> Books { get; set; }
    }
}

我需要创建用户注册和用户登录。应用程序需要知道用户是否登录。

是否有一些最佳实践如何做到这一点?在会话中保存登录用户?

4

2 回答 2

2

没有必要弄乱Session对象。

由于您已经在使用 ASP.NET MVC,因此您AccountController的 Controllers 文件夹中可能有一个。该控制器具有基本的身份验证方法。

我建议您看一下 ASP.NET 团队的本教程,该教程解释并展示了如何在 ASP.NET MVC 中使用身份验证 + 授权。

创建新的 ASP.NET MVC 应用程序时,ASP.NET MVC 的默认 Visual Studio 项目模板会自动启用表单身份验证。它还会自动向项目添加一个预构建的帐户登录页面实现——这使得在站点中集成安全性变得非常容易。

NerdDinner 第 9 步:身份验证和授权

于 2013-01-01T23:16:53.863 回答
2

我会使用 ASP.NET 成员资格和角色提供者模型。如果您想使用自定义表来执行此操作,您可以创建一个从 Membership Provider 继承的类。您可以实施多种方法来支持更改密码、忘记密码等操作……但用于登录的方法是 ValidateUser

public sealed class MyMembershipProvider : MembershipProvider
{
    public override bool ValidateUser(string username, string password)
    {
        bool isValid = false;
        // your authentication logic here
        var ticket = new FormsAuthenticationTicket(
                    1,
                    YOUR_USER_ID_HERE,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    name,
                    FormsAuthentication.FormsCookiePath);

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                HttpContext.Current.Response.Cookies.Add(authCookie);

        return isValid;
    }
}

如果您希望有不同级别的用户,您还需要创建一个角色提供者。为此,您将从 RoleProvider 类继承。

public sealed class MyRoleProvider : RoleProvider
{
   // Implement logic here
}

要授权应用程序的某些区域,您将使用 Authorize 属性。

public class MyController : Controller
{
     [Authorize(Roles="Role1,Role2")]
     public ActionResult Index()
     {
         // Implement your code
     }
}

最后,您必须在 web.config 中进行一些配置才能使其使用您的提供程序。

<authentication mode="Forms">
  <forms loginUrl="~/Login" timeout="2880"/>
</authentication>
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="20">
  <providers>
    <clear/>
    <add name="MyMembershipProvider" type="Your.NameSpace.MyMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false"/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="MyRoleProvider" cacheRolesInCookie="true">
  <providers>
    <clear/>
    <add name="MyRoleProvider" type="Your.NameSpace.MyRoleProvider"/>
  </providers>
</roleManager>

您可以在 MSDN 上找到有关 memberhsip 和角色提供者的更多信息

于 2013-01-01T21:32:57.400 回答