You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Asp.Net Core MVC中实现自定义请求头校验以拦截不符合要求的请求?

Hey Stephan, let's tackle this problem step by step—restricting access to your ASP.NET Core MVC controllers to only requests with a custom Authorization header is totally doable, and I'll walk you through the most straightforward, maintainable ways to implement it.

Method 1: Custom Action Filter (Flexible for Controllers/Actions)

This approach is perfect if you want to apply the check to specific controllers, individual actions, or globally across all endpoints.

  1. Create a filter class that inherits from ActionFilterAttribute, and override the OnActionExecuting method to validate the header:
using Microsoft.AspNetCore.Mvc.Filters;

public class CustomAuthFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Check if the Authorization header exists
        if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out var authHeader))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        // Split the header into auth type and token (expected format: "CustomType YourToken")
        var authParts = authHeader.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (authParts.Length != 2 || !authParts[0].Equals("YourCustomAuthType", StringComparison.OrdinalIgnoreCase))
        {
            // Invalid auth type or malformed header
            context.Result = new UnauthorizedResult();
            return;
        }

        // Validate the token (replace this with your actual token logic)
        var token = authParts[1];
        if (!IsTokenValid(token))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        base.OnActionExecuting(context);
    }

    // Replace this with your real token validation (e.g., check against DB/cache/JWT)
    private bool IsTokenValid(string token)
    {
        return !string.IsNullOrEmpty(token) && token.StartsWith("Valid_AppToken_"); // Example condition
    }
}
  1. Apply the filter:
  • To a single controller or action:
[CustomAuthFilter]
public class SecureController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
  • Globally (all controllers/actions):
    Add this to your Program.cs when configuring services:
builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<CustomAuthFilter>();
});
Method 2: Custom Middleware (Global Request Check)

If you want to validate the header for every incoming request (not just controller endpoints), middleware is the way to go.

  1. Create the middleware class:
public class CustomAuthMiddleware
{
    private readonly RequestDelegate _next;

    public CustomAuthMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Validate the Authorization header
        if (!context.Request.Headers.TryGetValue("Authorization", out var authHeader))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("Missing required Authorization header");
            return;
        }

        var authParts = authHeader.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (authParts.Length != 2 || !authParts[0].Equals("YourCustomAuthType", StringComparison.OrdinalIgnoreCase))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("Invalid Authorization type");
            return;
        }

        var token = authParts[1];
        if (!IsTokenValid(token))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("Invalid or expired token");
            return;
        }

        // If all checks pass, pass the request to the next middleware
        await _next(context);
    }

    private bool IsTokenValid(string token)
    {
        // Replace with your actual token validation logic
        return !string.IsNullOrEmpty(token) && token.Length > 15; // Example check
    }
}
  1. Register the middleware in Program.cs (order matters—place it after UseRouting and before UseAuthorization):
var app = builder.Build();

// ... other middleware (e.g., static files, error handling)

app.UseRouting();

// Add your custom auth middleware here
app.UseMiddleware<CustomAuthMiddleware>();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
Quick Tips
  • Replace YourCustomAuthType with your actual custom authorization scheme name (e.g., MyAppAuth).
  • For token validation, you can integrate JWT, OAuth2, or your own internal token system—just swap out the IsTokenValid method with your business logic.
  • If you need role/claim-based authorization later, you can combine these approaches with ASP.NET Core's built-in IAuthorizationService for more granular control.

内容的提问来源于stack exchange,提问作者Stephan Pich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 07:54:08