C# 使用Web API返回匿名类型
使用MVC时,返回临时Json很容易C# 使用Web API返回匿名类型,c#,json,asp.net-web-api,json.net,C#,Json,Asp.net Web Api,Json.net,使用MVC时,返回临时Json很容易 return Json(new { Message = "Hello"}); 我正在用新的Web API寻找这个功能 public HttpResponseMessage<object> Test() { return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK); } 但是我不认为使用Web API有什么意
return Json(new { Message = "Hello"});
我正在用新的Web API寻找这个功能
public HttpResponseMessage<object> Test()
{
return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
但是我不认为使用Web API有什么意义,如果我不返回HttpResponseMessage
,我最好还是坚持使用香草MVC。如果我尝试使用:
public HttpResponseMessage<object> Test()
{
return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
公共HttpResponseMessage测试()
{
返回新的HttpResponseMessage(新的{Message=“Hello”},HttpStatusCode.OK);
}
它序列化整个HttpResponseMessage
有谁能告诉我一个解决方案,我可以在
HttpResponseMessage
中返回匿名类型?如果您使用泛型,您应该能够实现这一点,因为它将为您的匿名类型提供一个“类型”。然后可以将序列化程序绑定到该文件
public HttpResponseMessage<T> MakeResponse(T object, HttpStatusCode code)
{
return new HttpResponseMessage<T>(object, code);
}
公共httpresponsemessagemakeresponse(T对象,HttpStatusCode代码)
{
返回新的HttpResponseMessage(对象、代码);
}
如果类中没有DataContract
或DataMebmer
属性,它将依赖于序列化所有公共属性,而这些属性应该完全符合您的要求
(直到今天晚些时候我才有机会测试它,如果有什么东西不起作用,请告诉我。)这在Beta版中不起作用,但在最新版本(基于构建)中起作用,因此它可能是RC的方式。你能行
public HttpResponseMessage Get()
{
return this.Request.CreateResponse(
HttpStatusCode.OK,
new { Message = "Hello", Value = 123 });
}
您可以使用JsonObject执行以下操作:
dynamic json = new JsonObject();
json.Message = "Hello";
json.Value = 123;
return new HttpResponseMessage<JsonObject>(json);
dynamicjson=newjsonobject();
json.Message=“你好”;
json.Value=123;
返回新的HttpResponseMessage(json);
您也可以尝试:
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());
你可以用一个。(使用System.Dynamic添加,
)
可以将动态对象封装在返回对象中,如
public class GenericResponse : BaseResponse
{
public dynamic Data { get; set; }
}
然后在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;
}
[路由(“api/MethodReturingDynamicData”)]
[HttpPost]
公共HttpResponseMessageMethodReturingDynamicData(请求到请求)
{
HttpResponseMessage响应;
尝试
{
GenericResponse结果=新建GenericResponse();
动态数据=新的ExpandooObject();
data.Name=“Subodh”;
result.Data=Data;//或在此处分配任何动态数据;//
response=Request.CreateResponse(HttpStatusCode.OK,结果);
}
捕获(例外情况除外)
{
LogCompleteException(例如,“GetAllListMetadataForApp”、“Post”);
HttpError myCustomError=新的HttpError(ex.Message){{{“IsSuccess”,false};
返回请求.CreateErrorResponse(HttpStatusCode.OK,myCustomError);
}
返回响应;
}
这个答案可能来得有点晚,但从今天起,WebApi 2
已经推出,现在做你想做的事情更容易了,你只需要做:
public object Message()
{
return new { Message = "hello" };
}
沿着管道,它将根据客户的偏好(
Accept
标题)被序列化为xml
或json
。希望这能帮助那些在ASP.NET Web API 2.1中遇到这个问题的人,您可以用一种更简单的方式来完成:
public dynamic Get(int id)
{
return new
{
Id = id,
Name = "X"
};
}
您可以在web API 2中阅读更多关于此的信息。您可以使用新的IHttpActionResult来替代HttpResponseMessage,然后返回一个简单的Json对象:(类似于MVC)
public IEnumerable GetList()
{
使用(var context=new DBContext())
{
返回context.SPersonal.Select(m=>
新的
{
FirstName=m.FirstName,
LastName=m.LastName
}).取(5)ToList();
}
}
}
当前版本中的情况似乎并非如此。我在执行上述操作时收到HTTP 500。在4.0 RTM中工作正常。重要的是,只有默认的json序列化程序才能处理匿名对象的序列化。默认的xml序列化程序将出错,所以请确保您返回的匿名对象是您的客户端知道要发送的,并且在头中包含accept:application/json。浏览器和Chrome一样,在默认情况下也会请求xml,所以请注意..@doker您使用的是什么版本的WebApi,我只是使用VS 2015和WebApi25.2.3从我的控制器粘贴了这些代码,最后我删除了xml格式化程序,因为大多数返回的对象无论如何都不会序列化为xml。@doker在您的情况下,当您尝试执行我建议的操作时,会发生什么?你有没有得到一个例外
?对我来说是最好的答案。我需要一种从WebAPI操作返回SlimJSON的方法,而无需在不同的位置/程序集中生成额外的内容。工作起来很有魅力!谢谢
public object Message()
{
return new { Message = "hello" };
}
public dynamic Get(int id)
{
return new
{
Id = id,
Name = "X"
};
}
public IHttpActionResult GetJson()
{
return Json(new { Message = "Hello"});
}
public IEnumerable<object> GetList()
{
using (var context = new DBContext())
{
return context.SPersonal.Select(m =>
new
{
FirstName= m.FirstName ,
LastName = m.LastName
}).Take(5).ToList();
}
}
}