Tom el Safadi
Tom el Safadi

Reputation: 6766

How Can I Throw an Error Within Asp.Net Middleware

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?

Upvotes: 4

Views: 1140

Answers (1)

John H
John H

Reputation: 14655

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

Upvotes: 4

Related Questions