c#asp.net地图中间件用于路由

时间:2017-05-03 14:50:45

标签: c# asp.net

我正在实现一些我只想在特定路线上运行的中间件

/api

还有一些其他中间件总是应该运行,有些是在api特定的中间件之前和之后。我在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);

加载中间件的顺序很重要,所以我想保留这个顺序。 app.UseCookieAuthMiddleware();应仅在以/ api开头的网址上运行,例如"/api, /api/test, /api?test"。 我看到app.Map是一个选项,但是如何确保添加app.Map之后的所有其他中间件。

编辑:当地图跳过以下行时的示例:

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();
}

我的中间件:

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>();
    }
}

我可以通过始终运行中间件来解决问题,并在middleware.invore中检查请求URL是否像“/ 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
       }
  }

但我想知道如何恰当地使用地图功能。

0 个答案:

没有答案