c# - 如何在 asp.net mvc 中使用 {SiteName} 处理 [Authorize]

标签 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();

所以在我尝试 code/debug/code/debug 路线之前寻求任何帮助!

最佳答案

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);
        }
    }
}

关于c# - 如何在 asp.net mvc 中使用 {SiteName} 处理 [Authorize],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707122/

相关文章:

c# - Razor 中的简单 html 与扩展方法(偏好)

c# - 使用全局程序集缓存 (GAC) - 以其设计的方式

c# - GCHandle.Alloc 除了保持对对象的引用之外还会做任何事情吗?

asp.net - OWIN Katana 与 ASP.NET Core Docker 容器相比如何

c# - 将依赖添加为 DLL 或添加为项目

asp.net - 使用 Excel/VBA 抓取 ASP 页面

c# - 你如何获取字符串中的第一个字母?

c# - 编码(marshal)包含可变长度数组的 C 结构

c# - 扩展 Telerik 客户端模板列并获取通过的值

c# - 使用 jQuery 的 DataAnnotation 客户端