C# ASP.NET MVC RestAPI:在接收正文和参数之前处理标头



通常在网络协议中,请求标头被预处理,然后处理请求正文。 对于HTTP,我不确定,但我想知道是否有任何方法可以在请求正文及其参数之前处理标头?

以 C# 方式说话,在 Controller 方法被触发之前是否有任何方法可以处理请求标头?

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

答案是肯定的,您可以使用操作过滤器。 https://learn.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.
}
}

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

结果 - 设置 结果 使操作方法和后续操作筛选器的执行短路。

你可以像这样找到你的标题

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
}

最新更新