如何在 Asp.Net 中间件中抛出错误

How Can I Throw an Error Within Asp.Net Middleware

我正在使用自定义中间件来检查每个请求的 header 中的租户,如下所示:

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);
}