返回匿名类型的网络API [英] Returning anonymous types with Web API

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

问题描述

当使用MVC,返回即席的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.

我跟这个<一个替代这href=\"https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib.Formatting.JsonNet/JsonNetFormatter.cs\">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" };
 }

但我没有看到使用Web API如果我不回来了Htt presponseMessage点,我会过得更好香草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);
}

它系列化整体的Htt presponseMessage。

It serializes the whole HttpResponseMessage.

任何人都可以引导我到soloution在那里我可以内返回匿名类型一的Htt presponseMessage?

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

推荐答案

这不会在Beta版本的工作,但它在最新位支持(从的 HTTP://aspnetwebstack.$c$cplex.com 的),所以它可能会为钢筋混凝土的方式。你可以做

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 });
}

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

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