简体   繁体   English

如何使用ASP.NET MVC4登录?

[英]How to login using ASP.NET MVC4?

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: Web.config文件:

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

...

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

Controllers/AccountController.cs: 控制器/ AccountController.cs:

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

Views/Account/Login.aspx: 查看/帐号/的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 ? 您使用的是ASP.NET MVC 4的Internet模板吗? 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. 如果没有,我建议您使用Internet模板创建一个新的ASP.NET MVC项目,打开帐户控制器并查看和方法。

As @user1 has rightly said one of the way you could do this is using 正如@ user1正确地说,你可以这样做的方法就是使用

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

But as you say, you are using ASP.NET MVC 4. You should use WebSecurity Class. 但正如您所说,您使用的是ASP.NET MVC 4.您应该使用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: 大多数工作都是使用WebSecurity助手的以下方法和属性完成的:

Further Reading : 进一步阅读:

I suspect you are not setting the forms authentication cookie which is why the the redirect is not working. 我怀疑你没有设置表单身份验证cookie,这就是重定向不起作用的原因。 Ideally, in your login method, you will verify the username and password using some logic and when you are satisfied that the user is legit, you have to set the forms authentication cookie and then redirect the user 理想情况下,在您的登录方法中,您将使用某些逻辑验证用户名和密码,当您确信用户是合法的时,您必须设置表单身份验证cookie然后重定向用户

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

If you don't set the authentication cookie, the redirect will not work since the request will still be treated as an unauthenticated request and the user will be sent back to the login page. 如果您未设置身份验证cookie,则重定向将不起作用,因为请求仍将被视为未经身份验证的请求,并且用户将被发送回登录页面。 You can find more information on forms login here 您可以在此处找到有关表单登录的更多信息

http://msdn.microsoft.com/en-us/library/xdt4thhy%28v=vs.71%29.aspx http://msdn.microsoft.com/en-us/library/xdt4thhy%28v=vs.71%29.aspx

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

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