如何使用 ASP.NET MVC 6 重定向未经授权的用户

How to redirect unauthorized users with ASP.NET MVC 6

我想知道如何重定向用户。我有一个 Controller Index() 并且我希望只有角色 "Student" 的用户可以进入那里!所以我使用

[Authorize(Roles="Student")]

我想知道如何将没有此角色的用户重定向到主页

MVC5(及更早版本):

您可以通过更改 web.config 上的 loginUrl 属性来实现。将其更改为所需的路线:

<authentication mode="Forms">
  <forms loginUrl="~/Home/Index" timeout="2880" />
</authentication>

MVC6:

在 MVC6 中你可以试试这个(在 Startup.cs 内):

public void ConfigureServices(IServiceCollection services)
{       
    services.Configure<CookieAuthenticationOptions>(options =>
    {
        options.LoginPath = new PathString("/Home/Index");
    });
}

您是否尝试为此使用会话?

我猜你有登录页面,然后在登录后尽快对会话进行分类

那么简单的 If 条件就可以了。

<%If Session("userRole")="Student" Then%>
  This is the text version of the page
<%Else%>
  Response.Redirect("notavailablepage.html")
<%End If%>

有一种适用于 MVC5 的方法。我认为它也适用于 MVC6。
在您的控制器中,像这样创建一个自定义 Auth 方法。

    public class YourCustomAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // If they are authorized, handle accordingly
        if (this.AuthorizeCore(filterContext.HttpContext))
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            // Otherwise redirect to your specific authorized area
            filterContext.Result = new RedirectResult("~/YourController/Unauthorized");
        }
    }
}

然后把你的数据注释改成

[YourCustomAuthorize(Roles = "Admin")]
public class UserController : Controller
{
     // Omitted for brevity
}