使用 Web API 返回匿名类型 [英] Returning anonymous types with Web API

查看:21
本文介绍了使用 Web API 返回匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 MVC 时,返回 adhoc Json 很容易.

When using MVC, returning adhoc Json was easy.

return Json(new { Message = "Hello"});

我正在寻找具有新 Web API 的此功能.

I'm looking for this functionality with the new Web API.

public HttpResponseMessage<object> Test()
{    
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}

这会引发异常,因为 DataContractJsonSerializer 无法处理匿名类型.

This throws an exception as the DataContractJsonSerializer can't handle anonymous types.

我已经用这个 JsonNetFormatter 基于 Json.Net.如果我使用

I have replaced this with this JsonNetFormatter based on Json.Net. This works if I use

 public object Test()
 {
    return new { Message = "Hello" };
 }

但如果我不返回 HttpResponseMessage,我不认为使用 Web API 有什么意义,我最好坚持使用 vanilla MVC.如果我尝试使用:

but I don't see the point of using Web API if I'm not returning HttpResponseMessage, I would be better off sticking with vanilla MVC. If I try and use:

public HttpResponseMessage<object> Test()
{
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}

它序列化整个HttpResponseMessage.

谁能指导我找到可以在 HttpResponseMessage 中返回匿名类型的解决方案?

Can anyone guide me to a solution where I can return anonymous types within a HttpResponseMessage?

推荐答案

这在 Beta 版本中不起作用,但在最新版本中起作用(从 http://aspnetwebstack.codeplex.com),所以它可能是 RC 的方式.你可以这样做

This doesn't work in the Beta release, but it does in the latest bits (built from http://aspnetwebstack.codeplex.com), so it will likely be the way for RC. You can do

public HttpResponseMessage Get()
{
    return this.Request.CreateResponse(
        HttpStatusCode.OK,
        new { Message = "Hello", Value = 123 });
}

这篇关于使用 Web API 返回匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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