C # asp.net map middleware for route

I am implementing some middleWare that I only want to use on a specific route

/api

      

There are several other middleware that should always run, some before and some after certain api middleware. My code in Startup.cs:

app.UseStaticFiles();
app.UseIdentity();
//some more middleware is added here

//my own middleware which should only run for routes at /api
app.UseCookieAuthMiddleware();

//some more middleware is added here
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

app.UseKendo(env);

      

The order in which the middleware is loaded is important, so I want to keep that order. app.UseCookieAuthMiddleware();

should only work on urls that start with / api, eg. "/api, /api/test, /api?test"

... I saw app.Map was an option, but how to make sure all other middleware after app.Map is added.

edit: example where the map skips the following lines:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   app.UseIdentity();
   //some more middleware is added here
   app.Map("/api", HandleApiRoutes);


   //lines below are skipped ONLY when map is used.
   //some more middleware should be added here 
   app.UseKendo(env);
}


private static void HandleApiRoutes(IApplicationBuilder app)
{
    app.UseCookieAuthMiddleware();
}

      

My middleware:

public class CookieCheckMiddleWare
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext context)
    {

        Debug.WriteLine("Middleware is called" );

        //Call the next delegate/middleware in the pipeline this._next(context) is called no errors.
        return this._next(context);
    }
}

public static class CookieCheckMiddleWareMiddlewareExtensions
{
    public static IApplicationBuilder UseCookieAuthMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CookieCheckMiddleWare>();
    }
}

      

I can just solve the problem by always running the middleware and checking in middleware.invore to check if the request url is "/ api":

  public Task Invoke(HttpContext context)
  {
       var url = context.Request.Path.Value.ToString();
       var split = url.Split('/');
       if (split[1] == "api") //should do a extra check to allow /api?something
       {
          //middleware functions
       }
  }

      

But I like to know how to use the map function.

+3


source to share





All Articles