且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何登录使用ASP.NET MVC4?

更新时间:2022-11-06 08:56:47

您使用ASP.NET MVC 4的网络模板?如果不是,我建议你创建网络模板创建一个新的ASP.NET MVC项目,打开账户控制器,有一个外观和方法。

作为@ USER1正确地说,你可以做到这一点是使用的方法之一

  FormsAuthentication.SetAuthCookie(用户名,真实);
 返回重定向(RETURNURL);

但正如你说,你正在使用ASP.NET MVC 4,您应该使用WebSecurity类。

例如:

  WebSecurity.Login(model.UserName,model.Password);
返回RedirectToAction(指数,家);

大部分的工作是使用WebSecurity帮手以下方法和属性来完成:


  • WebSecurty.UserExists, WebSecurity.CreateUserAndAccount.这些方法让你判断一个人是否已经注册和注册。


  • WebSecurty.IsAuthenticated.此属性允许您确定当前用户是否登录,这是有用的,如果他们没有在已经登录的用户重定向到登录页面。


  • WebSecurity.Login, WebSecurity.Logout.这些方法或退出登录用户。


  • WebSecurity.CurrentUserName.此属性是有用的显示当前用户的登录名(如果用户登录)。


  • WebSecurity.ConfirmAccount.如果设置了注册确认电子邮件此方法非常有用。 (详情载于博客文章使用了ASP.NET网页安全确认的功能描述。)


延伸阅读:

Here are some bits of code from my attempt. It does not work; after "logging in", the user isn't redirected to the home/index page, but the login page just reloads.

Web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" />
</authentication>

...

<defaultDocument>
  <files>
    <add value="~/Account/Login"/>
  </files>
</defaultDocument>

Controllers/AccountController.cs:

public class AccountController : Controller
{
    //
    // GET: /Account/Login
    public ActionResult Login()
    {
        return View();
    }
}

Views/Account/Login.aspx:

<asp:Login ID="login" runat="server" DestinationPageUrl="~/Views/Home/Index.aspx">
    ...
</asp:Login>

Are you using the internet template of ASP.NET MVC 4 ? if not I suggest you create a new ASP.NET MVC project with internet template, open the Account Controller and have a look and the methods.

As @user1 has rightly said one of the way you could do this is using

 FormsAuthentication.SetAuthCookie(username, true);
 return Redirect(returnurl);

But as you say, you are using ASP.NET MVC 4. You should use WebSecurity Class.

For example :

WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");

Most of the work is done using the following methods and properties of the WebSecurity helper:

Further Reading :