1

我尝试使用 json 调用 web 服务,当我调用没有异常参数的 web 服务时,它的工作,但是当我尝试发送参数时,我得到了一个错误:

这是我的代码:

function GetSynchronousJSONResponse(url, postData) 
{

    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    url = url + "?rnd=" + Math.random(); // to be ensure non-cached version

    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    var responseText = xmlhttp.responseText;
    return responseText;
}


function Test() 
{
    var result = GetSynchronousJSONResponse('http://localhost:1517/Mysite/Myservice.asmx/myProc', '{"MyParam":"' + 'test' + '"}');
    result = eval('(' + result + ')');
    alert(result.d);
}

这是错误:

System.InvalidOperationException:请求格式无效:application/json;字符集=utf-8。

在 System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()

在 System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest

怎么了 ?

提前致谢 。

4

3 回答 3

2

你可以在 javascript 中调用 web 服务,它将返回 JSON :)

$.ajax({
    type: "POST",
    url: '<%=ResolveUrl("~/DesktopModules/TECH_WEBRTC/Service/Users.asmx/Getprovider")%>',
    data: JSON.stringify({id:'a'}),
            contentType: "application/json; charset=utf-8",

            dataType: "json",
            processData: false,
            success: (function (providerlist) {


                var obj = jQuery.parseJSON(providerlist.d);
                providers(obj);
            }
            ),
            error: function (data)
            {

            }
 });




namespace TECH_WEBRTC.Service
 {
/// <summary>
/// Summary description for Users
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class Users : System.Web.Services.WebService
{



    [WebMethod]
    //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
    public string Getprovider(string id)
    {

        List<Comman1> obj = new List<Comman1>();
        JavaScriptSerializer js = new JavaScriptSerializer();

        obj.Add(new Comman1{id="1"});
            obj.Add(new Comman1{id="2"});
            obj.Add(new Comman1 { id = "2" });

            //Context.Response.Write(js.Serialize(obj.ToList()));

        return js.Serialize(obj.ToList());

    }
}

}

它工作正常:)

于 2016-09-27T05:39:07.940 回答
1

据我所知,您的应用程序不能接受application/json作为发布数据格式。改用application/x-www-form-urlencoded并将您的 JSON 设置为请求参数,然后您可以使用以下命令访问Request.Params["key"]

xmlhttp.open("POST", url, false); 
xmlhttp.setRequestHeader(
    "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"
); 
xmlhttp.send("json="+encodeURIComponent(postData)); 
var responseText = xmlhttp.responseText; 
return responseText; 

此外,正如我在评论中提到的,您可以删除以下行:

url = url + "?rnd=" + Math.random(); // to be ensure non-cached version   

POST 请求不会被缓存,并且将 GET 参数与 POST 请求一起使用通常是不好的做法。

于 2010-02-02T15:07:45.153 回答
1

通过将这些行添加到服务器的 web.config 中,我已经解决了类似的问题:

<handlers>
  <add name="ScriptHandlerFactory" verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" />
</handlers>

查看此页面:http: //msdn.microsoft.com/en-us/library/bb763183.aspx

于 2011-09-20T11:49:28.057 回答