jQuery 如何在 Web API 控制器上返回 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14231877/
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
How to return Json object on Web API Controller
提问by BizApps
I used this below code on my asp.net controller to return Json object on my Ajax on javascript
我在我的 asp.net 控制器上使用下面的代码在我的 Ajax 上返回 Json 对象的 javascript
public JsonResult myMethod()
{
// return a Json Object, you could define a new class
return Json(new
{
Success = true, //error
Message = "Success" //return exception
});
}
Jquery-Ajax:
Jquery-Ajax:
$.ajax({
type: "POST",
url: url_ ,
data: search,
success: function(data) {
//Show Json Properties from Controller ( If Success == false show exception Message from controller )
if (data.Success)
{
alert(data.Message); //display success
}
else
{
alert(data.Message) //display exception
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + XMLHttpRequest.responseText);
},
dataType: 'json'
});
How can this be done on Web Api Controller?
这如何在 Web Api 控制器上完成?
Can you give me some examples or url as reference.
你能给我一些例子或网址作为参考。
Thanks and Regards
感谢致敬
回答by tpeczek
ASP.NET Web API works with a little bit different philosophy. You should return just an entity (or set of entities) and it is up to content negotiation mechanism to return it to the client in the format which he has requested. You can read more about content negotiation here:
ASP.NET Web API 的工作原理有点不同。您应该只返回一个实体(或一组实体),并且由内容协商机制以他请求的格式将其返回给客户端。您可以在此处阅读有关内容协商的更多信息:
You can of course bypass the content negiotiation by returning a HttpResponseMessage
. In this case yo need to serialize the object into JSON yourself (basics of this approach are also described in the article mentioned above).
您当然可以通过返回HttpResponseMessage
. 在这种情况下,您需要自己将对象序列化为 JSON(上面提到的文章中也描述了这种方法的基础知识)。
回答by Darrel Miller
If you create yourself a new HttpContent class for delivering JSON, like...
如果您为自己创建一个新的 HttpContent 类来传递 JSON,例如...
public class JsonContent : HttpContent {
private readonly MemoryStream _Stream = new MemoryStream();
public JsonContent(object value) {
Headers.ContentType = new MediaTypeHeaderValue("application/json");
var jw = new JsonTextWriter( new StreamWriter(_Stream));
jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.Serialize(jw, value);
jw.Flush();
_Stream.Position = 0;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) {
return _Stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length) {
length = _Stream.Length;
return true;
}
}
Then you can do,
那么你可以这样做,
public HttpResponseMessage Get() {
return new HttpResponseMessage() {
Content = new JsonContent(new
{
Success = true, //error
Message = "Success" //return exception
})
};
}
just like you do with JsonResult.
就像你对 JsonResult 所做的一样。
回答by Jason Frank
After reading tpeczek's answer, Darrel Miller's answer, and their comment conversation in tpeczek's answer, I wanted get more guidance about when or why I might want to use Web Api and its content negotiation mechanism. tpeczek's link is informative and useful, but I found a couple other write-ups that were more geared at comparing the use of Web Api (and its content negotiation) with, say, plain MVC 4 controller actions that return JsonResult
. Here are the ones that I found useful to making such a decision. One of the author concludes that he prefers using plain MVC 4 controllers while the other author prefers using Web Api controllers:
在阅读了 tpeczek 的回答、Darrel Miller 的回答以及他们在 tpeczek 的回答中的评论对话后,我想获得更多关于何时或为什么要使用 Web Api 及其内容协商机制的指导。tpeczek 的链接信息丰富且有用,但我发现了一些其他的文章,它们更适合比较 Web Api(及其内容协商)的使用与返回的普通 MVC 4 控制器操作JsonResult
。以下是我发现对做出这样的决定有用的那些。其中一位作者得出结论,他更喜欢使用普通的 MVC 4 控制器,而另一位作者则更喜欢使用 Web Api 控制器:
Building a Public HTTP API for Data
I believe there is one correction needed in the above author's post. In there he mentions that,
我相信在上述作者的帖子中需要进行一项更正。他在那里提到,
"...every [Controller] method that begins with 'Get' is automatically associated to the GET verb. Does it sound great? It is, but it also means that you can't have two methods whose name begin with 'Get' in the same controller class."
“...每个以 'Get' 开头的 [Controller] 方法都会自动关联到 GET 动词。听起来不错吗?确实如此,但这也意味着您不能有两个名称以 'Get' 开头的方法在同一个控制器类中。”
According to this answer, you can indeed have multiple 'Get' methods in the same controller if you specify an ActionName
attribute. Now here's the second post:
根据这个答案,如果您指定一个ActionName
属性,您确实可以在同一个控制器中拥有多个“Get”方法。现在这是第二篇文章: