我正在使用自定义中间件来检查每个请求的标头中的租户,如下所示:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句