覆盖MVC POST请求的内容标头

Wee*_*bie 10 .net model-view-controller content-type http asp.net-web-api

我对MVC很新,所以我希望有一个解决我的问题的方法.我正在使用第三方硬件与我的MVC Web API进行通信.硬件以JSON格式发送请求,我可以完全提取.但是,由于冲突,我正在将这些请求的参数更改为绑定模型对象.

例如

        Public Function POSTRequest(Action As String, Stamp As String) As HttpResponseMessage
           ...
        End Function

        Public Function POSTRequest(Action As String, OpStamp As String) As HttpResponseMessage
           ...
        End Function
Run Code Online (Sandbox Code Playgroud)

所以这两种方法共享同一张名片,因此它们都不能存在于同一个控制器中.

因此,我创建了模型绑定对象来代替这些参数.问题是,一旦我这样做,Web API会抱怨请求说"Content-Type"没有定义.看一下,第三方硬件不会向请求发送内容类型.在网上看,我发现这导致浏览器将其视为内容类型"application/octet-stream".然后,这不能将其转换为定义为参数的绑定对象.

我们无法控制第三方硬件,因此我们无法为这些请求定义内容类型.所以,我的问题是,有没有办法拦截这些请求并为它们添加内容类型?或者甚至是另一种方式?

Arn*_*lay 5

我想你可以使用ActionFilterAttribute.请参阅文件:创建自定义操作过滤器.

在您的情况下,您可以使用以下示例(在C#中,因为我的VB技能已过时).它Content-Type使用application/json值覆盖任何请求标头 .请注意,您可能需要对其进行增强以支持各种类型HttpContent(例如,我不认为这应该用于MultiPart请求).

public class UpdateRequestAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext.Request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        base.OnActionExecuting(actionContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将此属性添加到控制器类,例如:

[UpdateRequest]
public class HomeController : ApiController
{
    //[...]
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,对Home控制器的所有请求都将Content-Type被覆盖.


或者,您也可以编写自定义的HTTP消息处理程序,它在管道中很早就被调用,并且不会局限于特定的控制器.检查以下图片以了解服务器如何处理请求.

ASP.net服务器端处理程序

例如,如果当前为空,则此消息处理程序将请求设置Content-Typeapplication/json.

public class CustomMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content.Headers.ContentType == null)
        {
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        }
        return base.SendAsync(request, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,以下是如何更新WebApiConfig以便将消息处理程序添加到管道:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new CustomMessageHandler());

        // Other configuration not shown... 

    }
}
Run Code Online (Sandbox Code Playgroud)