[英]How to enforce Url route values in MVC Pipeline in a multi tenant app
我有以下默认路线
url: "{tenant}/{controller}/{action}/{id}",
defaults: new { tenant="not_set", controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { tenant= new TenantConstraint()}
我有一个user1,该用户只能访问tenant1/{Controller}/{action}
。 如果用户尝试将网址修改为tenantNoAccess/{Controller}/{action}
,我希望他被自动重定向到tenant1/{Controller}/{action}
。
我可以在ActionFilter中执行此操作,但我不希望请求在mvc管道中走得那么远。 我想在请求尝试到MapRequestHandler()之前做一些事情。
我在想,也许是在Application_PostAuthenticateRequest()中?...
protected void Application_AuthenticateRequest(object o, EventArgs args)
{
var context = HttpContext.Current;
var httpContext = new HttpContextWrapper(HttpContext.Current);
var user = context.User;
var request = context.Request;
var requestUrl = request.Url;
var reqContext = request.RequestContext;
if (user.Identity.IsAuthenticated)
{
var usr = (System.Security.Claims.ClaimsPrincipal)user;
string correctTenant = GetCorrectTenantForUser(usr);
if (!reqContext.RouteData.Values["tenant"].Equals(correctTenant))
{
//stuck here. How to change the URL without referencing a 3rd party Url rewrite module?
}
else
{
//tenant matches
return;
}
}
else
{
//
}
}
在RouteConfig中,您可以添加一个路由处理程序。
routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional} ).RouteHandler = new LandingPageRouteHandler();
在routehandler中,您可以进行所需的检查并设置适当的控制器,动作等。
public class LandingPageRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext Context)
{
if ( <perform checks)
{
Context.RouteData.Values["controller"] = <whateveryouwant>;
Context.RouteData.Values["action"] = <whateveryouwant>;
Context.RouteData.Values["id"] = <whateveryouwant>;
}
return base.GetHttpHandler(Context);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.