问题
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;
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);
}
}
With the types
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"
}
This works fine, as well
Content-Type: application/xml
body:
<?xml version="1.0" encoding="utf-8"?>
<InfoRequest>
<Id>ACARG021</Id>
<Total>20</Total>
<Status>Confirmed</Status>
</InfoRequest>
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>
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);
回答1:
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.
来源:https://stackoverflow.com/questions/39919822/web-api-not-able-to-bind-model-for-post-with-utf-16-encoded-xml