使用Web API返回匿名类型

Mag*_*pie 71 c# json json.net asp.net-web-api

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

return Json(new { Message = "Hello"});
Run Code Online (Sandbox Code Playgroud)

我正在使用新的Web API寻找此功能.

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

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

我有这个替换此JsonNetFormatter基于Json.Net.如果我使用,这可行

 public object Test()
 {
    return new { Message = "Hello" };
 }
Run Code Online (Sandbox Code Playgroud)

但是我没有看到使用Web API的重点,如果我不回来HttpResponseMessage,我会更好地坚持使用vanilla MVC.如果我尝试使用:

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

它将整个序列化HttpResponseMessage.

任何人都可以指导我一个解决方案,我可以在其中返回匿名类型HttpResponseMessage

car*_*ira 80

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

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

  • 重要提示,只有默认的json序列化程序才能处理匿名对象的序列化.默认的xml序列化程序将出错,因此请确保返回客户端知道发送的匿名对象:标题中的application/json.浏览器就像Chrome一样,默认情况下也会请求xml,所以只需要抬头.. (16认同)

Lui*_*iso 16

这个答案可能会有点迟,但截至今天WebApi 2已经出来了,现在你可以更容易地做你想做的事,你只需要这样做:

public object Message()
{
    return new { Message = "hello" };
}
Run Code Online (Sandbox Code Playgroud)

沿着管道,它将被序列化为xmljson根据客户的偏好(Accept标题).希望这有助于任何人绊倒这个问题


Ser*_*usM 6

你可以使用JsonObject:

dynamic json = new JsonObject();
json.Message = "Hello";
json.Value = 123;

return new HttpResponseMessage<JsonObject>(json);
Run Code Online (Sandbox Code Playgroud)


Jam*_*ruk 5

您可以使用ExandoObject.(添加using System.Dynamic;)

[Route("api/message")]
[HttpGet]
public object Message()
{
    dynamic expando = new ExpandoObject();
    expando.message = "Hello";
    expando.message2 = "World";
    return expando;
}
Run Code Online (Sandbox Code Playgroud)


D.B*_*D.B 5

在Web API 2中,您可以使用新的IHttpActionResult(它代替HttpResponseMessage),然后返回一个简单的Json对象:(类似于MVC)

public IHttpActionResult GetJson()
    {
       return Json(new { Message = "Hello"});
    }
Run Code Online (Sandbox Code Playgroud)

  • 对我来说最好的答案。我需要一种方法来从 Web API Action 返回细长的 JSON,而无需在不同的地方/程序集中产生额外的东西。奇迹般有效!谢谢。 (4认同)