如何在网页API返回控制JSON对象 [英] How to return Json object on Web API Controller

查看:160
本文介绍了如何在网页API返回控制JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个低于code我的asp.net遥控器上的JavaScript的我的Ajax返回JSON对象

I used this below code on my asp.net controller to return Json object on my Ajax on 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的阿贾克斯:

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

如何才能实现这一基于Web API控制器做了什么?

How can this be done on Web Api Controller?

您能给我一些例子或网址作为参考。

Can you give me some examples or url as reference.

感谢和问候

推荐答案

如果您自己创建的交付JSON新HttpContent类,如...

If you create yourself a new HttpContent class for delivering JSON, like...

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

就像你做JsonResult。

just like you do with JsonResult.

这篇关于如何在网页API返回控制JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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