最佳答案
我正在创建一个多租户网站,主机为客户的网页。URL 的第一部分将是一个字符串,用于标识客户端,该字符串在 Global.asax 中使用以下 URL 路由方案定义:
"{client}/{controller}/{action}/{id}"
使用/foo/Home/Index 这样的 URL 可以很好地工作。
但是,在使用[ Authorize ]属性时,我想重定向到一个也使用相同映射方案的登录页面。因此,如果客户机是 foo,登录页面将是/foo/Account/Login,而不是 web.config 中定义的固定/Account/Login 重定向。
MVC 使用 HttpUnauthorizedResult 返回一个401未授权状态,我推测这会导致 ASP.NET 重定向到 web.config 中定义的页面。
那么有人知道如何覆盖 ASP.NET 登录重定向行为吗?或者通过创建一个自定义授权属性在 MVC 中重定向会更好?
编辑-回答: 。我认为自定义身份验证属性是最好的解决方案:
public class ClientAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization( AuthorizationContext filterContext )
{
base.OnAuthorization( filterContext );
if (filterContext.Cancel && filterContext.Result is HttpUnauthorizedResult )
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "client", filterContext.RouteData.Values[ "client" ] },
{ "controller", "Account" },
{ "action", "Login" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}