C# 使用 Web API 返回匿名类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10123371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning anonymous types with Web API
提问by Magpie
When using MVC, returning adhoc Json was easy.
使用 MVC 时,返回 adhoc Json 很容易。
return Json(new { Message = "Hello"});
I'm looking for this functionality with the new Web API.
我正在使用新的 Web API 寻找此功能。
public HttpResponseMessage<object> Test()
{
return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
This throws an exception as the DataContractJsonSerializercan't handle anonymous types.
这将引发异常,因为DataContractJsonSerializer无法处理匿名类型。
I have replaced this with this JsonNetFormatterbased on Json.Net. This works if I use
我有这个替换此JsonNetFormatter基于Json.Net。如果我使用,这有效
public object Test()
{
return new { Message = "Hello" };
}
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:
但如果我不回来HttpResponseMessage,我看不到使用 Web API 的意义,我最好坚持使用 vanilla MVC。如果我尝试使用:
public HttpResponseMessage<object> Test()
{
return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
It serializes the whole HttpResponseMessage.
它序列化整个HttpResponseMessage.
Can anyone guide me to a solution where I can return anonymous types within a HttpResponseMessage?
任何人都可以指导我找到一个解决方案,我可以在其中返回匿名类型HttpResponseMessage吗?
采纳答案by carlosfigueira
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
这在 Beta 版本中不起作用,但在最新版本中起作用(从http://aspnetwebstack.codeplex.com构建),因此它可能是 RC 的方式。你可以做
public HttpResponseMessage Get()
{
return this.Request.CreateResponse(
HttpStatusCode.OK,
new { Message = "Hello", Value = 123 });
}
回答by Michael Edenfield
You should be able to get this to work if you use generics, as it will give you a "type" for your anonymous type. You can then bind the serializer to that.
如果你使用泛型,你应该能够让它工作,因为它会给你一个匿名类型的“类型”。然后,您可以将序列化程序绑定到该序列化程序。
public HttpResponseMessage<T> MakeResponse(T object, HttpStatusCode code)
{
return new HttpResponseMessage<T>(object, code);
}
If there are no DataContractor DataMebmerattributes on your class, it will fall back on serializing all public properties, which should do exactly what you're looking for.
如果您的类上没有DataContractorDataMebmer属性,它将退回序列化所有公共属性,这应该完全符合您的要求。
(I won't have a chance to test this until later today, let me know if something doesn't work.)
(直到今天晚些时候我才有机会测试这个,如果有什么不起作用,请告诉我。)
回答by SeriousM
you can use JsonObject for this:
您可以为此使用 JsonObject:
dynamic json = new JsonObject();
json.Message = "Hello";
json.Value = 123;
return new HttpResponseMessage<JsonObject>(json);
回答by leojh
You may also try:
您也可以尝试:
var request = new HttpRequestMessage(HttpMethod.Post, "http://leojh.com");
var requestModel = new {User = "User", Password = "Password"};
request.Content = new ObjectContent(typeof(object), requestModel, new JsonMediaTypeFormatter());
回答by James Lawruk
You could use an ExandoObject. (add using System.Dynamic;)
您可以使用ExandoObject。(添加using System.Dynamic;)
[Route("api/message")]
[HttpGet]
public object Message()
{
dynamic expando = new ExpandoObject();
expando.message = "Hello";
expando.message2 = "World";
return expando;
}
回答by Subodh Pushpak
You can encapsulate dynamic object in returning object like
您可以将动态对象封装在返回对象中,例如
public class GenericResponse : BaseResponse
{
public dynamic Data { get; set; }
}
and then in WebAPI; do something like:
然后在 WebAPI 中;做类似的事情:
[Route("api/MethodReturingDynamicData")]
[HttpPost]
public HttpResponseMessage MethodReturingDynamicData(RequestDTO request)
{
HttpResponseMessage response;
try
{
GenericResponse result = new GenericResponse();
dynamic data = new ExpandoObject();
data.Name = "Subodh";
result.Data = data;// OR assign any dynamic data here;//
response = Request.CreateResponse<dynamic>(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
ApplicationLogger.LogCompleteException(ex, "GetAllListMetadataForApp", "Post");
HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } };
return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError);
}
return response;
}
回答by Luiso
This answer may come bit late but as of today WebApi 2is already out and now it is easier to do what you want, you would just have to do:
这个答案可能来得有点晚,但截至今天WebApi 2已经出来了,现在做你想做的更容易,你只需要做:
public object Message()
{
return new { Message = "hello" };
}
and along the pipeline, it will be serialized to xmlor jsonaccording to client's preferences (the Acceptheader). Hope this helps anyone stumbling upon this question
并且沿着管道,它将被序列化为xml或json根据客户端的首选项(Accept标头)。希望这可以帮助任何在这个问题上绊倒的人
回答by Francisco Goldenstein
In ASP.NET Web API 2.1 you can do it in a simpler way:
在 ASP.NET Web API 2.1 中,您可以通过一种更简单的方式来实现:
public dynamic Get(int id)
{
return new
{
Id = id,
Name = "X"
};
}
You can read more about this on https://www.strathweb.com/2014/02/dynamic-action-return-web-api-2-1/
您可以在https://www.strathweb.com/2014/02/dynamic-action-return-web-api-2-1/上阅读更多相关信息
回答by D.B
In web API 2 you can use the new IHttpActionResult which is a replacement for HttpResponseMessage and then return a simple Json object: (Similiar to MVC)
在 Web API 2 中,您可以使用新的 IHttpActionResult,它是 HttpResponseMessage 的替代品,然后返回一个简单的 Json 对象:(类似于 MVC)
public IHttpActionResult GetJson()
{
return Json(new { Message = "Hello"});
}

