asp.net-core-mvc - 关闭异步响应
问题描述
我正在尝试关闭当前响应,但是当我尝试HttpContext.Response.Body.Close()
并且Response.End()
不存在时没有任何反应。
我试图实现这一点的原因是由于遗留验证器函数会写入错误并关闭响应,或者至少停止父 WebAPI 方法。
例子:
private async Task Register_v2()
{
//Read JSON to object
UserRegisterRequest userRegisterRequest = Request.ReadBody().FromJson<UserRegisterRequest>();
//Validate object (legacy static method with a lot of logic)
//Validate() should end the response if object not validated
userRegisterRequest.Validate(isJson: true, isThrowHttpError: true);
//Code still reaches here and request does not close
string test = "hey I'm alive";
}
我可以以某种方式使用中间件解决这个问题吗?
谢谢
解决方案
There are two ways to terminate the Request pipeline
.
- Use
app.Run
inStartup.Configure
- Do not invoke
_next(context)
inMiddleware.InvokeAsync
For your scenario, you could try second option by determining whether to invoke _next(context)
.
public class FirstMiddleware
{
private readonly RequestDelegate _next;
public FirstMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync($"This is { GetType().Name }");
//decide whether to invoke line below based on your business logic
//await _next(context);
bool isValid = userRegisterRequest.Validate(isJson: true, isThrowHttpError: true);
//change userRegisterRequest.Validate to reutrn whether the model is valid
if(!isValid)
{
await context.Response.WriteAsync($"Model is not valid");
}
else
{
await _next(context);
}
}
}
推荐阅读
- mysql - 应该在 my.ini 配置中更改哪些设置来更改存储数据库的文件夹?
- google-cloud-firestore - Cloud Firestore 如何查找包含特定文档 ID 的子集合的所有文档?
- reactjs - 在 Docker 中以生产模式运行 create-react-app
- docker - 使用 blob 从 DOCKER API 获取图像
- java - 将巨大的整数文件(在一行中)拆分为具有内存限制的排序块
- rust - 是否有基于静态分析的 compile_error 替代方法(例如通过优化器)
- android - 如何以 MVVM 模式将参数值传递给 ViewModel?
- sql - 如何将json数组转换为postgresql中的行
- sql - Rails 动态“Where”子句
- vbscript - 最近一次 Windows 更新后服务器超时