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

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

问题描述

我在我的 asp.net 控制器上使用下面的代码在我的 Ajax 上使用 javascript 返回 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-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'
});

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

How can this be done on Web Api Controller?

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

Can you give me some examples or url as reference.

感谢和问候

推荐答案

如果您为自己创建了一个新的 HttpContent 类来传递 JSON,例如...

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

然后你就可以了,

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

就像你对 JsonResult 所做的一样.

just like you do with JsonResult.

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

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