如何在Web API Controller上返回Json对象

Biz*_*pps 23 jquery jquery-mobile asp.net-mvc-4 asp.net-web-api visual-studio-2012

我在我的asp.net控制器上使用下面的代码在javascript上返回我的Ajax上的Json对象

public JsonResult myMethod()
{
    // return a Json Object, you could define a new class
    return Json(new
    {
        Success = true, //error
        Message = "Success" //return exception
    });
}
Run Code Online (Sandbox Code Playgroud)

jQuery的阿贾克斯:

$.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'
});
Run Code Online (Sandbox Code Playgroud)

如何在Web Api控制器上完成?

你能给我一些例子或网址作为参考.

感谢致敬

tpe*_*zek 30

ASP.NET Web API使用一些不同的哲学.您应该只返回一个实体(或一组实体),并且由内容协商机制将其以请求的格式返回给客户端.您可以在此处详细了解内容协商:

你当然可以通过返回a来绕过内容的失措HttpResponseMessage.在这种情况下,你需要自己将对象序列化为JSON(这种方法的基础也在上面提到的文章中描述).


Dar*_*ler 25

如果你自己创建一个新的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

那你可以做到,

      public HttpResponseMessage Get() {
            return new HttpResponseMessage() {
                Content = new JsonContent(new
                {
                    Success = true, //error
                    Message = "Success" //return exception
                })
            };
        }
Run Code Online (Sandbox Code Playgroud)

就像你对JsonResult一样.

  • 为什么不使用Web API的默认序列化行为并直接返回您的类型并让框架处理序列化? (6认同)
  • @TedNyberg因为有时候控制你的线格非常重要.让序列化程序为您做出决定可以使您依赖于该序列化程序及其配置.对于Json而言,这不是一个问题而是XML,但它仍然是一个问题. (2认同)

Jas*_*ank 10

在阅读了tpeczek的回答,Darrel Miller的回答,以及他们在tpeczek的回答中的评论对话之后,我希望得到更多关于我何时或为什么要使用Web Api及其内容协商机制的指导.tpeczek的链接提供了丰富的信息和实用性,但我发现其他一些文章更适合将Web Api(及其内容协商)的使用与返回的普通MVC 4控制器操作进行比较JsonResult.以下是我发现做出这样决定有用的内容.其中一位作者得出结论,他更喜欢使用普通的MVC 4控制器而另一位作者更喜欢使用Web Api控制器:

为数据构建公共HTTP API

我相信上述作者的帖子需要进行一次修正.他在那里提到,

"...以'Get'开头的每个[Controller]方法都会自动与GET动词相关联.听起来不错吗?是的,但这也意味着你不能有两个名字以'Get'开头的方法在同一个控制器类中."

根据这个答案,如果指定一个ActionName属性,你确实可以在同一个控制器中有多个"Get"方法.现在这是第二篇文章:

ASP.NET Web API与ASP.NET MVC"API"