Change ASP.NET MVC Routes dynamically

我的梦境 提交于 2019-12-02 22:20:28

Considering the actual problem background, the usual approach is to include a dynamically created transaction number. It should be stored in a hidden form field as well as in the server side session dictionary and only be valid for exactly one request.

I think today a lot of frameworks provide such a security mechanism; whereas this attack type is known as Cross-Site-Request-Forgery (csrf).

I would consider to implement my own IRouteHandler and put some custom logic in my custom ControllerActionInvoker. How it would work ? The route table wouldn't dynamically change but you could check in your custom ControllerActionInvoker for a random parameter in the route path and invoke or not the corresponding action.

My route :

routes.Add 
( 
    new Route 
        ( 
            "blog/comment/{*data}", 
            new RouteValueDictionary(new {controller = "blog", action = "comment", data = ""}), 
            new MyRouteHandler() 
        ) 
); 

My I route handler :

    class MyRouteHandler : IRouteHandler 
{ 

public IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
        return new MyHttpHandler(requestContext); 
    } 
}`

My handler :

class MyHttpHandler : MvcHandler 
{ 
    public MyHttpHandler(RequestContext requestContext) : base(requestContext) 
    { 
    } 

    protected override void ProcessRequest(HttpContextBase httpContext) 
    { 
        IController controller = new BlogController(); 
        (controller as Controller).ActionInvoker = new MyActionInvoker(); 
        controller.Execute(RequestContext); 
    } }`

and my action ivoker where the custom logic for handling an action or not should be coded :

    class MyActionInvoker : ControllerActionInvoker 
{ 
    protected override ActionResult InvokeActionMethod(MethodInfo methodInfo, IDictionary<string, object> parameters) 
    { 

        var data = ControllerContext.RouteData.GetRequiredString("data"); 


 // put my custom logic to check whetever I'll handle the action or not. The data could be a parameter in the database for that purpose.

        return base.InvokeActionMethod(methodInfo, parameters); 
    } 
} 

I don't know it it's the best solution but for now it's the one that comes to my mind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!