2016-10-23 150 views
8

我正在尝试编写一个中间件来保持服务器上处理某些客户端路由。我看了很多定制的中间件类,它们会使回应短路。ASP.NET Core Response.End()?

context.Response.End(); 

我在intellisense中看不到End()方法。我如何终止响应并停止执行http管道?提前致谢!

public class IgnoreClientRoutes 
{ 
    private readonly RequestDelegate _next; 
    private List<string> _baseRoutes; 

    //base routes correcpond to Index actions of MVC controllers 
    public IgnoreClientRoutes(RequestDelegate next, List<string> baseRoutes) 
    { 
     _next = next; 
     _baseRoutes = baseRoutes; 

    }//ctor 


    public async Task Invoke(HttpContext context) 
    { 
     await Task.Run(() => { 

      var path = context.Request.Path; 

      foreach (var route in _baseRoutes) 
      { 
       Regex pattern = new Regex($"({route})."); 
       if(pattern.IsMatch(path)) 
       { 
        //END RESPONSE HERE 

       } 

      } 


     }); 

     await _next(context); 

    }//Invoke() 


}//class IgnoreClientRoutes 
+0

只是不叫'下一个()'。 – SLaks

回答

8

结束不再存在,因为经典的ASP.NET管道不再存在。中间件是管道。如果您希望在此时停止处理请求,请在不调用下一个中间件的情况下返回。这将有效地阻止管道。

好吧,不是完全的,因为堆栈将被解开,一些中间件仍然可以向响应写入一些数据,但你明白了。从你的代码中,你似乎想要避免执行中的其他中间件。

编辑:这里是如何在代码中做到这一点。

public class Startup 
{ 
    public void Configure(IApplicationBuilder app) 
    { 
     app.Use(async (http, next) => 
     { 
      if (http.Request.IsHttps) 
      { 
       // The request will continue if it is secure. 
       await next(); 
      } 

      // In the case of HTTP request (not secure), end the pipeline here. 
     }); 

     // ...Define other middlewares here, like MVC. 
    } 
} 
+0

如何在代码中做到这一点? – Geomorillo

+0

我看到代码感谢 – Geomorillo

2

终止方法不存在了。在你的中间件中,如果你调用下一个代理,那么它将转到下一个中​​间件来处理请求并继续,否则它会结束请求。以下代码显示调用next.Invoke方法的示例中间件,如果您省略,则响应将结束。

using System.Threading.Tasks; 
using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Logging; 

namespace MiddlewareSample 
{ 
    public class RequestLoggerMiddleware 
    { 
     private readonly RequestDelegate _next; 
     private readonly ILogger _logger; 

     public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) 
     { 
      _next = next; 
      _logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>(); 
     } 

     public async Task Invoke(HttpContext context) 
     { 
      _logger.LogInformation("Handling request: " + context.Request.Path); 
      await _next.Invoke(context); 
      _logger.LogInformation("Finished handling request."); 
     } 
    } 
} 

回到你的代码,你应该简单地从模式匹配的情况下返回。

看看到微软核心文档此文档了解详情:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware