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

标签 c# asp.net-mvc http-headers interceptor asp.net-apicontroller

通常在网络协议(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/

相关文章:

asp.net-mvc - Sammy.js 和 Knockout.js => 没有模板的模板?

c# - 如何更正运行 Controller 操作产生的路由?

http - cookie 中的域名

c# - 我的算法中找到每对的总和不整除 K 的最大子集的缺陷在哪里?

c# - orm 和 ADO.net 有什么区别?

c# - 将 chromedriver.exe 放在哪里以发布 Selenium WebDriver C#

c# - 工作实现单元

asp.net-mvc - 添加非mvc路由时Html.ActionLink构造错误链接

http - 设置 HTTP header

http - 页面中的最大http请求