WebApi 2 Odata控制器编码

时间:2014-06-30 12:11:33

标签: asp.net-mvc-5 odata asp.net-web-api2

如何调整WebApi2 Odata Controller,以与ApiController相同的方式序列化数据?为什么它将非Unicode字符从“č”替换为“\ u010d”?

例如

 public class PacientaiController : ODataController
    { ...
     // GET: odata/Pacientai
        [Queryable(MaxExpansionDepth = 8)]
        public  IHttpActionResult GetPacientai(ODataQueryOptions<Pacientas> queryOptions)
        {

结果

{
    "odata.metadata": "http://localhost:13248/odata/$metadata#Pacientai",
    "value": [{
        "Id": 1147146,
        "Vardas": "Edgaras",
        "Pavarde": "Me\u010dkauskas",
        "AK": "12341412341",
        "GimimoData": "1986-01-16T00:00:00"
    }]
}

如果我将控制器改为ApiController,就像这样

 public class PacientaiController : ApiController
    { ...
        [Queryable(MaxExpansionDepth = 8)]
        public  IHttpActionResult GetPacientai()
        {

结果如下:

{
    "Id": 1147146,
    "Vardas": "Edgaras",
    "Pavarde": "Mečkauskas",
    "AK": "12341412341",
    "GimimoData": "1986-01-16T00:00:00",
}

注意Field:Pavarde!

1 个答案:

答案 0 :(得分:3)

我们可以写一个消息处理程序:

public class StringRewriter : DelegatingHandler
{
    private static readonly JsonMediaTypeFormatter formatter;

    static StringRewriter()
    {
        formatter = new JsonMediaTypeFormatter();
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        if (response.Content == null || response.Content.Headers.ContentType == null ||
            response.Content.Headers.ContentType.MediaType != "application/json")
        {
            return response;
        }

        var stream = await response.Content.ReadAsStreamAsync();
        var token = JToken.ReadFrom(new JsonTextReader(new StreamReader(stream)));

        var content = new ObjectContent<JToken>(token, formatter);
        foreach (var header in response.Content.Headers)
        {
            content.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }

        response.Content = content;

        return response;
    }
}

并将其添加到WebApiConfig:

    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new StringRewriter());