ASP.NET通过WebMethod返回JSON对象

本文关键字:JSON 对象 返回 WebMethod NET 通过 ASP | 更新日期: 2023-09-27 18:00:23

我有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,这就是为什么我没有使用有效的方法)。

ASP.NET通过WebMethod返回JSON对象

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,但其他任何一个都应该正常工作。

此外,您可以更改签名,使其接受字符串作为唯一参数,然后在GetOrderInformation()中将该JSON字符串转换为OrderInformationRequest

我收到HTTP错误500。jobDetails是作为字符串发送的,但我没有在它周围加任何引号。