通常在网络协议(protocol)中,会预处理请求头,然后处理请求体。 对于 HTTP,我不确定,但我想知道是否有任何方法可以在请求正文及其参数之前处理 header ?
用 C# 的方式来说,在 Controller 方法被触发之前是否有任何方法可以处理请求 header ?
如果答案是肯定的,我想将客户端版本发送到我的服务器,以防它们不匹配发送客户端合适的响应。我想这样做,因为我的请求正文可能很大(例如 10MB),并且我想在等待接收整个 HTTP 请求之前预处理 header 。
最佳答案
答案是肯定的,您可以使用操作过滤器。 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.
}
}
根据文档,您可以覆盖操作上下文并短路结果,而无需进入 Controller 。
Result - setting Result short-circuits execution of the action method and subsequent action filters.
您可以像这样找到标题
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
}
关于C# ASP.NET MVC RestAPI : Process headers before body and and parameters are received,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59280357/