我有 ASP.NET 代码
public class OrderInformationResponse
{
public GetOrderLookupResponseType orderLookupResponse { get; set; }
}
[System.Web.Services.WebMethod]
public static OrderInformationResponse GetOrderInformation(string jobId, string userId, string jobDetails) {
OrderInformationResponse response = new OrderInformationResponse();
JobDetails jobDetailsEnum = (JobDetails)Enum.Parse(typeof(JobDetails), jobDetails);
response.orderLookupResponse = GetOrderLookup(jobId, userId);
return response;
}
我尝试从 jQuery 调用它:
$.ajax({
type: "POST",
url: "somePage.aspx/GetOrderInformation",
data: "{'jobId':" + jobId + ", " +
" 'userId':" + userId + ", " +
" 'jobDetails':" + jobDetails +
"}",
contentType: "application/json; charset=utf-8",
datatype: "json",
async: true,
cache: false,
success: function (msg) {
p_Func(msg); // This is a pointer to function.
}
});
GetOrderLookupResponseType
声明:
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.somewhere.uk/MessageContracts/OrderManagement/OrderInfo/2010/02")]
public partial class GetOrderLookupResponseType { ... }
我无法在客户端获取任何内容。在此之前,我尝试从另一个标记为 [WebMethod]
的方法返回 GetOrderLookupResponseType
并且它有效,但是当我尝试将其放入新创建的 OrderInformationResponse
它停止工作了。 (我计划用其他内容填充 OrderInformationResponse
,这就是我没有使用有效方法的原因)。
最佳答案
public class OrderInformationResponse
{
public GetOrderLookupResponseType orderLookupResponse { get; set; }
}
[System.Web.Services.WebMethod]
public static void GetOrderInformation(string jobId, string userId, string jobDetails)
{
OrderInformationResponse response = new OrderInformationResponse();
JobDetails jobDetailsEnum = (JobDetails)Enum.Parse(typeof(JobDetails), jobDetails);
response.orderLookupResponse = GetOrderLookup(jobId, userId);
string json = JsonConvert.SerializeObject(response); //I use Json.NET, but use whatever you want
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.Write(json);
}
ASP.NET Web 方法不能很好地处理 JSON 响应。因此将 JSON 直接写入输出并将签名设置为 void
。我用过Json.NET执行 JSON,但任何其他方法通常都应该可以工作。
此外,您还可以更改签名,使其接受字符串作为唯一参数,然后将该 JSON 字符串转换为 OrderInformationRequest
在GetOrderInformation()
.
关于c# - ASP.NET 通过 WebMethod 返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298651/