首页 > 解决方案 > 如何在 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 错误。我怎么能做到这一点?

标签: c#asp.net-coreasp.net-core-middleware

解决方案


感谢您的评论澄清您想要做什么。您的代码最终将如下所示:

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

推荐阅读