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?
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.
Added MvcRouteHandler and MvcApplicationBuilderExtensions in my project.
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...
}
In Startup.cs, changed app.UseMvc
to app.UseMyMvc
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With