如果他没有登录,如何将用户重定向到网站中的特定页面?

use*_*142 1 asp.net-mvc login http-redirect

标题说明了一切,我希望如此,如果用户试图导航到任何页面或访问网站中的任何内容以重定向到登录页面,那只有在他没有登录时才会这样.

这是我的简单登录代码:

public ActionResult login(MvcMobile.Models.Users x)
    {
        var user = db.Users.FirstOrDefault(u => u.username == x.username && u.password == x.password);


    if (user == null)
        ModelState.AddModelError("","username or password is wrong.");

    else
    {
        FormsAuthentication.SetAuthCookie(user.username, false);
        Response.Redirect("/");
    }
    return View(user);
}
Run Code Online (Sandbox Code Playgroud)

我试图将此代码放在主布局中,但我有一个无限重定向循环:P

 @if (User.Identity.IsAuthenticated)
                   {
          <p> Hi @User.Identity.Name</p>
                   }
                   else
                      {

                        Response.Redirect("~/home/login");
                    }
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

Dar*_*rov 7

[Authorize]属性装饰你的控制器/动作.或者,如果您希望将其应用于所有控制器,请将其添加为全局操作过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new AuthorizeAttribute());
}
Run Code Online (Sandbox Code Playgroud)

当然,通过这样做,您可能希望通过使用以下[AllowAnonymous]属性进行装饰来排除AccountController的身份验证:

然后在您的web.config中,将loginUrl表单身份验证标记的页面设置为指向所有匿名用户将被重定向到的登录页面:

<authentication mode="Forms">
    <forms loginUrl="~/home/login" />
</authentication>
Run Code Online (Sandbox Code Playgroud)