How Can I Throw an Error Within Asp.Net Middleware

778 Views Asked by At

I am using a custom middleware to check for the tenant in the header of every request like so:

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

In the above code I would like to throw a 401 error within the pipeline. How would I be able to do that?

1

There are 1 best solutions below

3
On BEST ANSWER

Thanks for your comments for clarifying what you want to do. Your code will end up looking something like this:

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