我正在創建一個承載客戶端頁面的多租戶網站。 URL的第一部分將是一個字符串,識別客戶端,使用下面的URL路由方案在Global.asax中定義:如何重定向到ASP.NET MVC中的動態登錄URL
"{client}/{controller}/{action}/{id}"
這工作得很好,用的URL如/富/首頁/索引。
但是,當使用[Authorize]屬性時,我想重定向到也使用相同映射方案的登錄頁面。因此,如果客戶端是foo,登錄頁面將是/ foo/Account/Login,而不是web.config中定義的固定/帳戶/登錄重定向。
MVC使用HttpUnauthorizedResult返回401未授權狀態,我認爲這會導致ASP.NET重定向到web.config中定義的頁面。
那麼有誰知道如何重寫ASP.NET登錄重定向行爲?或者,通過創建一個自定義授權屬性在MVC中重定向會更好嗎?
編輯 - 答:經過一番挖掘到.NET源,我決定自定義驗證屬性是最好的解決辦法:
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 }
});
}
}
}
具有路由做幾乎同樣的事情,所以我需要這個!謝謝! – 2008-12-27 21:20:41
謝謝,我試圖弄清楚如何做類似的事情。 – Chance 2010-02-03 02:34:06
它給了我自己實現的想法,非常感謝! – 2010-10-31 16:47:08