ASP.NET Core Response.End()?
本文关键字:End Response NET Core ASP | 更新日期: 2023-09-27 18:14:24
我正在尝试编写一个中间件,以防止某些客户端路由在服务器上被处理。我查看了许多自定义中间件类,它们会使
的响应短路。context.Response.End();
我在智能感知中没有看到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
End已经不存在了。. 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.
}
}
End方法已经不存在了。在中间件中,如果您在管道中调用下一个委托,它将转到下一个中间件处理请求并继续,否则它将结束请求。下面的代码显示了一个调用next的示例中间件。调用方法,如果省略该方法,则响应将结束。
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://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware