我如何在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);
}