如果ContentType不是JSON,我可以从.asmx Web服务返回JSON吗? [英] Can I return JSON from an .asmx Web Service if the ContentType is not JSON?

查看:83
本文介绍了如果ContentType不是JSON,我可以从.asmx Web服务返回JSON吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将使用ajax和jquery的表单发布到.asmx Web服务,并将Web服务中的值作为JSON返回.

I would like to post a form using ajax and jquery to a .asmx webservice and return the value from the webservice as JSON.

我正在使用ASP.NET 4.0.我知道,为了从Web服务返回JSON,需要设置以下内容(1)dataType:"json"(2)contentType:"application/json; charset = utf-8",(3)类型:"POST" (4)将数据设置为某物.我已经对此进行了测试,并且可以正常工作(即,我的Web服务将数据作为JSON返回)如果所有****** 都已设置**.

I'm using ASP.NET 4.0. I know that in order to return JSON from a webservice the following needs to be set (1) dataType: "json" (2) contentType: "application/json; charset=utf-8", (3) type: "POST" (4) set the Data to something. I have tested this and it works fine (i.e. my webservice returns the data as JSON) if all **four are set**.

但是,在我的情况下,我想发表一份标准表格,即test1 = value1& test2 = value2 所以contentType不是JSON,但我想返回JSON {test1:value1}.这似乎不起作用,因为contentType是" application/x-www-form-urlencoded "而不是" application/json; charset = utf-8 ".

But, lets say in my case I want to do a standard form post i.e. test1=value1&test2=value2 so the contentType is not JSON but I want back JSON {test1:value1}. This doesn't seem to work because the contentType is "application/x-www-form-urlencoded" not "application/json; charset=utf-8".

谁能告诉我为什么我不能这样做?对我来说,您必须明确地表示疯狂 发送JSON以返回JSON,但是如果您不使用JSON(即发布urlencoded内容类型),则网络服务将返回XML.

Can anyone tell me why I can't do this? It seems crazy to me that you have to explicitly send JSON to get JSON back, yet if you don't use JSON (i.e. post urlencoded contenttype) then the webservice will return XML.

任何见解都会受到赞赏:)

Any insights are greatly appreciated :)

推荐答案

如果您将使用WFC RESTfull服务而不是.asmx Web服务,则可以实现问题的所有要求.但是使用JSON作为输出的 Web服务要求,您至少要使用contentType: 'application/json'.在不同的地方,您可以找到一个原因-安全原因(请参阅JSON劫持).

If you will use WFC RESTfull Service instead of .asmx webservice you can implement all your requirements from your question. But usage of .asmx webservice with JSON as output required that you use at least contentType: 'application/json'. In different places you can find as a reason - security reason (see JSON Hijacking).

可能'x-www-form-urlencoded'并不是您真正的问题.如果使用dataType: "json",参数还将以"test1 = value1& test2 = value2"的形式发送!!!唯一的区别是,所有值均应使用JSON编码. jQuery 不对数据进行JSON编码. (您可以查看jQuery代码.)主要区别只是将在请求标头中显式设置"Accept:application/json".

Probably 'x-www-form-urlencoded' is not your real problem. If you use dataType: "json" the parameters will be also send in the form "test1=value1&test2=value2"!!! The only difference, that all values should be JSON encoded. And jQuery don't makes JSON encoding of the data. (You can look in the code of jQuery.) The main difference is only that "Accept: application/json" will be explicitly set in the request header.

查看 Jquery对httpget进行ajax调用我最近写的webmethod(c#)无法正常工作.在此帖子中,有人询问了GET请求的示例.但这几乎是相同的.唯一的区别是,编码后的数据将被附加到URL(用于GET请求).对于POST请求,数据将作为正文发送.顺便说一句,如果设置了"processData:false"(请参见 http://api.jquery.com/jQuery.ajax/)的GET数据也将在正文中发送.因此,请从 Jquery ajax调用httpget webmethod(c#)无法正常工作中读取我的代码示例.我希望您能收到想法,了解如何实现自己的目标.

Look at JQuery ajax call to httpget webmethod (c#) not working which I wrote recently. In this post was asked example of GET request. But it is almost the same. The only difference is, that data after encoding will be appended to the URL (for GET request). For POST request the data will be send in body. By the way if one set "processData: false" (see http://api.jquery.com/jQuery.ajax/) the GET data will be also send inside of body. So read my code example from JQuery ajax call to httpget webmethod (c#) not working. I hope you receive ideas how you can implement what you will.

我认为您在为.asmx网络服务调用编码复杂数据时遇到问题.这是带有复杂"数据的示例:

I think you had problems with encoding complex data for your .asmx webservice call. Here is example with "complex" data:

[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData AjaxGetMore (InputData input) {
    return new OutputData () {
        id = input.id,
        message = new List { "it's work!", "OK!" },
        myInt = new int[] { input.myInt[0] + 1, input.myInt[1] + 1, 20, 75 },
        myComplexData = new InternalData () { blaBla = "haha", iii = new int[] { 1, 2, 3, 4, 5 } }
    };
}

其中

public class InternalData {
    public string blaBla { get; set; }
    public int[] iii { get; set; }
}
public class OutputData {
    public string id { get; set; }
    public List message { get; set; }
    public int[] myInt { get; set; }
    public InternalData myComplexData { get; set; }
}
public class InputData {
    public string id { get; set; }
    public int[] myInt { get; set; }
    public InternalData data { get; set; }
}

并在客户端

var myData = { id: "li1234", myInt: [100, 200], data : {blaBla: "Hahhh!", iii: [10,20,30]}}
var myDataForjQuery = {input:$.toJSON(myData)};
$.ajax({
    type: "GET",
    url: "/Service1.asmx/AjaxGetMore", // + idAsJson,
    data: myDataForjQuery, // idAsJson, //myData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        // var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
        alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt); 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});

($.toJSON来自JSON插件) 您可以根据需要将此示例修改为HTTP POST.

($.toJSON come from the JSON plugin ) You can modify this example to HTTP POST, if you want.

另一个小建议.如果您使用jQuery 1.4.x,则可以尝试使用无"作为dataType.请参阅文档:如果未指定任何内容,则jQuery将根据响应的MIME类型智能地尝试获取结果(XML MIME类型将生成XML,在1.4 JSON中将生成JavaScript对象,在1.4脚本中将执行脚本,其他任何内容都将以字符串形式返回)"

One more small advice. If you use jQuery 1.4.x you can try use 'none' as dataType. See documentation: "If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string)"

最诚挚的问候

这篇关于如果ContentType不是JSON,我可以从.asmx Web服务返回JSON吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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