Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call controller and action from custom middleware

I'm new to ASP.NET 5 and the middleware classes. What I'm trying to create is a middleware class that reads incoming URL requests. Based on that I either want to let it go through and do a normal Route lookup, or I want my middleware class to call a specific controller/action from my Web API class.

What I currently have is the following. I think the comments in the code explains what I'm trying to achieve.

public class RouteMiddleware
{
    private readonly RequestDelegate _next;

    public RouteMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if(httpContext.Request.QueryString.Value == "test")
        {
            // Call custom Controller / Action
            // Then, don't do any more route resolving, since we already have the right controller/action
        }
        else
        {
            // Continue like normal
            await _next.Invoke(httpContext);
        }
    }
}

How can I do this in my middleware class?

like image 405
Vivendi Avatar asked Nov 10 '22 06:11

Vivendi


1 Answers

I think one way of doing this is by having own implementation of IRouter. Here is what I did as a test to have my own RouteHandler and it worked well for me.

  1. Added MvcRouteHandler and MvcApplicationBuilderExtensions in my project.

  2. Used Mynamespace.MvcRouteHandler in UseMvc method of MvcApplicationBuilderExtensions and renamed the method to UseMyMvc.

    public static IApplicationBuilder UseMyMvc(this IApplicationBuilder app,Action<IRouteBuilder> configureRoutes)
        {
            MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
            var routes = new RouteBuilder
            {
                DefaultHandler = new MyNamespace.MvcRouteHandler(),
                ServiceProvider = app.ApplicationServices
            };
         //..... rest of the code of this method here...
        }
    
  3. In Startup.cs, changed app.UseMvc to app.UseMyMvc

  4. Then in RouteAsync method of MyNamespace.MvcRouteHandler, set controller and action based on custom logic.

      context.RouteData.Values["area"] = "MyArea";
      context.RouteData.Values["controller"] = "MyController";
      context.RouteData.Values["action"] = "MyAction";
    
like image 57
eadam Avatar answered Nov 15 '22 10:11

eadam