C# ASP.NET MVC RestAPI:在接收 body 和参数之前处理 headers

C# ASP.NET MVC RestAPI: Process headers before body and and parameters are received

通常在网络协议中,header个请求被预处理,然后body个请求将被处理。 如果是 HTTP,我不确定,但我想知道在 body 请求及其参数之前是否有任何方法可以处理 header?

以 C# 方式交谈,是否有任何方法可以在触发或不触发控制器方法之前处理请求 header?

如果答案是肯定的,我想将客户端版本发送到我的服务器,以防它们不匹配发送客户端合适的响应。我想这样做,因为我的请求 body 可能会很大(例如 10MB),我想在等待接收整个 HTTP 请求之前预处理 header。

答案是肯定的,您可以使用动作过滤器。 https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1#action-filters

public class MySampleActionFilter : IActionFilter
{
    public void OnActionExecuting (ActionExecutingContext context)
    {
        // Do something before the action executes.
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}

根据文档,您可以覆盖操作上下文并使结果短路,而无需进入控制器。

Result - setting Result short-circuits execution of the action method and subsequent action filters.

您可以这样找到您的headers

var headers = context.HttpContext.Request.Headers;

// Ensure that all of your properties are present in the current Request
if(!String.IsNullOrEmpty(headers["version"])
{
     // All of those properties are available, handle accordingly

     // You can redirect your user based on the following line of code
     context.Result = new RedirectResult(url);
}
else
{
     // Those properties were not present in the header, redirect somewhere else
}