c# - 如何在 Asp.Net 中间件中引发错误
问题描述
我正在使用自定义中间件在每个请求的标头中检查租户,如下所示:
public TenantInfoMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
TenantInfoService tenantInfoService = context.RequestServices.GetRequiredService<TenantInfoService>();
// Get tenant from request header
var tenantName = context.Request.Headers["Tenant"];
if (!string.IsNullOrEmpty(tenantName))
tenantInfoService.SetTenant(tenantName);
else
tenantInfoService.SetTenant(null); // Throw 401 error here
// Call the next delegate/middleware in the pipeline
await _next(context);
}
在上面的代码中,我想在管道中抛出 401 错误。我怎么能做到这一点?
解决方案
感谢您的评论澄清您想要做什么。您的代码最终将如下所示:
public async Task InvokeAsync(HttpContext context)
{
TenantInfoService tenantInfoService = context.RequestServices.GetRequiredService<TenantInfoService>();
// Get tenant from request header
var tenantName = context.Request.Headers["Tenant"];
// Check for tenant
if (string.IsNullOrEmpty(tenantName))
{
context.Response.Clear();
context.Response.StatusCode = (int)StatusCodes.Status401Unauthorized;
return;
}
tenantInfoService.SetTenant(tenantName);
await _next(context);
}
推荐阅读
- tensorflow - 我可以用 pytorch 训练(优化)f1 分数损失吗
- python - Python递归函数检查列表中的所有数字是否都是偶数
- javascript - 无法在我的反应应用程序中加载背景图像
- c - 链表相同检查
- javascript - 如何让 $node index.js 在我的命令行中运行 index.js?
- shell - 如何从终端对文件运行 vim 命令?
- scala - 如何将排名特征类型字段添加到scala中的索引?
- python - 正则表达式替换无法在 Python 中用正则表达式变量替换
- python - Python requests 模块卡在 requests.get() 上并超时
- windows - 从 Windows 中的文件中清除键和值对