Web API无法使用utf-16编码的XML绑定POST的模型 [英] Web API not able to bind model for POST with utf-16 encoded XML
问题描述
我有一个带有 POST
方法的简单Web API控制器,该控制器接受一个对象.当客户端以 JSON
形式发布数据时,API可以正常工作.即使使用 encoding ="utf-8"
将数据作为 XML
发送时,该模型也可以无缝绑定(我在 WebApiConfig
中添加了以下行使用 Xml序列化
而不是 DataContract
)
I have a simple Web API controller with a POST
method, that accepts an object. When the clients posts data as JSON
the API works fine. Even when data is sent as XML
with encoding="utf-8"
, the model binds seamlessly (I have added the following line in WebApiConfig
to use Xml Serialization
instead of DataContract
)
config.Formatters.XmlFormatter.UseXmlSerializer = true;
下面是我的ApiController:
Below is my ApiController:
public class InfoController : ApiController
{
public HttpResponseMessage Post(InfoRequest infoRequest)
{
//do work and return something
return Request.CreateResponse(HttpStatusCode.Accepted, infoRequest != null);
}
}
使用类型
public class InfoRequest
{
public string Id { get; set; }
public int Total { get; set; }
public Status Status { get; set; }
}
public enum Status
{
None = 0,
Confirmed,
Cancelled
}
现在,当客户端根据数据集发出请求时,它可以正常工作
Now when client makes request following set of data, it works fine
Content-Type: application/json
body:
{
"Id": "ACARG021",
"Total": 20,
"Status": "Confirmed"
}
这也很好
Content-Type: application/xml
body:
<?xml version="1.0" encoding="utf-8"?>
<InfoRequest>
<Id>ACARG021</Id>
<Total>20</Total>
<Status>Confirmed</Status>
</InfoRequest>
但是,当使用 UTF-16 发布XML时,模型绑定失败,并且控制器方法将 null
传递给它./p>
But, when a XML is posted with UTF-16 the model binding fails and the controller method gets null
passed to it.
Content-Type: application/xml; charset=utf-16
//Accept-Charset: utf-16 //Edit: wrong header, removed
body:
<?xml version="1.0" encoding="utf-16"?>
<InfoRequest>
<Id>ACARG021</Id>
<Total>20</Total>
<Status>Confirmed</Status>
</InfoRequest>
正如其他一些SO帖子中所建议的那样,将其添加到 WebApiConfig
并没有帮助
As suggested in some other SO posts, adding this to the WebApiConfig
doesn't help
Encoding utf16 = Encoding.GetEncoding("utf-16");
config.Formatters.XmlFormatter.SupportedEncodings.Add(utf16);
推荐答案
在服务器端,这应该可以立即使用.所以我想问题将是您的POST.内容类型标头应具有正确的编码.仅将XML本身中的标头更改为encoding ="utf-16"是不够的.试试:
On server side this should work out of the box. So I guess problem will be your POST. Content type header should have correct encoding. It is not enough to change header in XML itself to encoding="utf-16". Try:
Content-Type: application/xml; charset=utf-16
您还需要实际以该编码发送数据,而不仅仅是更改标头.
You also need to actually send data in that encoding not just change the header.
这篇关于Web API无法使用utf-16编码的XML绑定POST的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!