简体   繁体   中英

How do I send JSON to Asp.NET Webservice?

I have a javascript object that I am serializing using JSON2 library. I am then trying to pass this JSON string to a ASP.net webservice. I have changed the webmethod to try several different parameter configurations but they all result in a '500 - Internal Server Error'

Can someone give me a clue?

 function postDataToService(data) {
    $.ajax({
        url: "http://localhost:2686/DataCollectionService.asmx/StoreDataOut",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: data,
        success: showSuccessNotice,
        error: showFailureNotice,
        dataType: "json"
    });

} //postdatatoservice

function convertDataToJSON(jsObj) {

    return JSON.stringify({ list: jsObj });

} //converdatatojson

Web Service:

 [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 DataCollectionService : WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string StoreDataOut(List<string> list)
    {
        return "Complete";
        //model functionality
    }
}

I got it..

Step 1 : I wrapped the JS object in another object that contains a property that matches the parameter name at the web method. Notive the quotes around the

return JSON.stringify({'json':jsObj});

Step 2 I then serialized this new 'wrapper' object with JSON.stringify().

Step 3 Parameter name at web method matched posted json property name. Type is 'object'

 public string StoreDataOut(object json)
    {

    }

I used the code you provided and was able to post to the webservice without issues.

Some questions:

  1. What does data look like?
  2. What is the 500 server error? Can you browse the webservice directly without errors? http://localhost:2686/DataCollectionService.asmx/StoreDataOut
  3. I noticed in your data to send you never call convertDataToJSON() was this a typo? If not perform the ajax post like the following:


   $.ajax({
            url: "http://localhost:2686/DataCollectionService.asmx/StoreDataOut",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: convertDataToJSON(data),
            success: showSuccessNotice,
            error: showFailureNotice,
            dataType: "json"
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM