如何在asp.net mvc中使用{SiteName}处理[授权]

时间:2013-05-23 06:35:37

标签: c# asp.net asp.net-mvc visual-studio-2012 authorization

给出一个mvc4,它在路由中有{sitename}参数,如此

routes.MapRoute(
    "Sites", // Route name
    "{sitename}/{controller}/{action}/{id}", // URL with parameters
    new { sitename = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
);

并且除了AccountController和任何其他使用[Authorize]属性的重定向到

之外,一切正常
 ~/Account/Login 

而不是

 ~/{sitename}/Account/Login 

一致性和美学性

有没有办法改变这个?显而易见的答案是创建自定义AuthorizeAttribute但大多数示例,例如ASP.NET MVC 4 custom Authorize attribute - How to redirect unauthorized users to error page?的答案 只需致电

 base.HandleUnauthorizedRequest();

所以在我尝试代码/调试/代码/调试路由之前寻找任何帮助!

1 个答案:

答案 0 :(得分:0)

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var sitename = filterContext.RouteData.Values["sitename"] as string;
        if (!string.IsNullOrEmpty(sitename))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "account",
                action = "login",
                sitename = sitename,
            });
            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}