自动添加的Content-Type将传入的HTTP请求,如果失踪 [英] Automatically add Content-Type to incoming HTTP requests if missing

查看:669
本文介绍了自动添加的Content-Type将传入的HTTP请求,如果失踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.Net的WebAPI服务,让嵌入式设备中的半实时传输数据。

I'm developing an ASP.Net WebAPI service to allow embedded devices to transfer data in semi-realtime.

这些设备将是一个封端的无线宽带计划,这意味着低的数据消费用途是该项目的一个要求。

These devices will be on a capped wireless broadband plan, which means that low data consumption usage is a requirement for this project.

该设备将通过JSON格式HTTP发送数据。
此刻,我有的内容类型:应用程序/ JSON在标题中,效果很好。

The devices will send data through HTTP in JSON format. At the moment, I include "Content-Type: application/json" in the header, which works well.

不过,我想它是precious字节(和数据使用计划),以通过线路每次发送这些几个字节的浪费。
我可以100%肯定,此刻发送的数据将通过连接JSON $ C $的CD,所以我宁愿让服务器假定它丢失时的Content-Type。

However, I'm thinking it is a waste of precious bytes (and data usage plan) to send these few bytes over the wire everytime. I can be 100% sure, at the moment that the data sent will be encoded by JSON, so I would rather have the server assume the Content-Type when it is missing.

不过,如果我忽略它,我的帖子控制器做没有触发了当客户端的职位给他们。
他们的声明这样:

However, if I omit it, my Post controllers do no trigger anymore when the client posts to them. They are declared like that:

public HttpResponseMessage Post([FromBody] MyEvent myEvent)

在短,我想要做的就是自动添加,在服务器端,内容类型,以客户端会忽略加传入的HTTP请求,或者让我的控制器工作的另一种方法并自动反序列化JSON消息,甚至与Content-Type头条目丢失。

In short, what I'm trying to do is to automatically add, on the server-side, the Content-Type to the incoming HTTP requests that the client would have omitted to add, or another way of making my controllers work and automatically deserialize the JSON message, even with that Content-Type header entry is missing.

我希望有可能是对的WebAPI项目源$ C ​​$ C文件或配置在那里我可以配置?

I'm hoping there might be a source code file or configuration on the WebAPI project where I could configure that?

先谢谢了。

推荐答案

试试这个。

public class ConTypeFilter:DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {        
        if ( request.Content.Headers.ContentType==null)
        {
            request.Content.Headers.ContentType=new MediaTypeHeaderValue("application/json");
        }
        return base.SendAsync(request, cancellationToken);
    }
}

而在你的的Application_Start()添加以下

GlobalConfiguration.Configuration.MessageHandlers.Add(new ConTypeFilter());

感谢这篇文章

这篇关于自动添加的Content-Type将传入的HTTP请求,如果失踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆