Change ASP.NET MVC Routes dynamically

前端 未结 2 1532
温柔的废话
温柔的废话 2021-02-02 01:04

usually, when I look at a ASP.Net MVC application, the Route table gets configured at startup and is not touched ever after.

I have a couple of questions on that but th

相关标签:
2条回答
  • 2021-02-02 01:36

    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).

    0 讨论(0)
  • 2021-02-02 01:44

    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.

    0 讨论(0)
提交回复
热议问题