0

我在 ASP.NET Web 表单项目中有一个 Web 服务,我正在尝试将数据发布到 Web 服务上的一个方法,然后返回一个 JSON 对象而不是默认的 XML。

我为示例简化的 Web 服务方法如下所示:

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public DataControl.JSONMessage NavigationItemsUpdate(string description, int id, string linkText)
    {

            DataControl.JSONMessage response = new DataControl.JSONMessage();
            response.Name = "Item Update";
            return response;
        }
    }  

通过 AJAX 提交以下 POST

 linkText=Skill+AquisitionAaAa&sequence=5&description=Learn+new+game+skills&uid=7&oper=edit&id=7

使用默认内容类型,但响应为 XML

 Content-Type   application/x-www-form-urlencoded; charset=UTF-8

回复:

 <?xml version="1.0" encoding="utf-8"?>
 <JSONMessage xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">
  <Name>Item Update</Name>
  <State>Failed</State>
  <Message0>Update</Message0>
 </JSONMessage>

我设法获得 JSON 响应的唯一方法是将 AJAX 调用的内容类型设置为

  contentType: "application/json",

它从 Asp.Net 的 Web 服务获得 JSON 响应,尽管它在读取 POST 参数时遇到问题并返回此异常

 {"Message":"Invalid JSON primitive: linkText.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

因为它期望 POST 是 JSON 而不是普通的 POST

我的问题是如何强制 Web 服务方法期望 POST 参数但以 JSON 响应?

4

0 回答 0