【问题标题】:How to handle [Authorize] with {SiteName} in asp.net mvc如何在 asp.net mvc 中使用 {SiteName} 处理 [Authorize]
【发布时间】:2013-05-23 15:45:29
【问题描述】:

给定一个 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();

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

【问题讨论】:

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


    【解决方案1】:
    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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-02
      • 2010-10-12
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多