Problems sending and receiving JSON between ASP.net web service and ASP.Net web client

[亡魂溺海] 提交于 2019-12-31 04:37:05

问题


You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem, If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error

The Web Service

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
    Dim Someone As New Person
    Someone.Name = "Bob"
    Someone.FavoriteColor = "Green"
    Someone.ID = WebInfo.WebUserID.ToString()
    Return Someone
End Function

The Web Client (set up to be send and receive JSON)

    public Person Test(int UserID, string url) {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json; charset=utf-8";
        StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
        sw.Write("{'WebInfo':{'WebUserID':1}}");  // this works from JQuery
        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
        Stream responseStream = webResponse.GetResponseStream();
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
        Person someone = (Person)jsonSerializer.ReadObject(responseStream);
        return someone;
    }

Has anyone out there done this successfully? Thanks


回答1:


Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below

public class WebServiceCallReturn {
    public string JSONResponse { get; set; }
    public string SimpleResponse { get; set; }
    public string Error { get; set; }
}

public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
    WebServiceCallReturn result = new WebServiceCallReturn();

    // create request
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.ContentType = "application/json; charset=utf-8";
    webRequest.Method = requestType;
    webRequest.Accept = "application/json; charset=utf-8";
    // add json data object to send
    if (requestType == "POST") {
        string json = "{ }";
        if (postData != null) {
            try {   // the serializer is fairly robust when used this way
                DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, postData);
                json = Encoding.UTF8.GetString(ms.ToArray());
            } catch {
                result.Error = "Error serializing post";
            }
        }
        webRequest.ContentLength = json.Length;
        StreamWriter sw;
        try {
            sw = new StreamWriter(webRequest.GetRequestStream());
        } catch (Exception ex) {
            // the remote name could not be resolved
            result.Error = ex.Message;
            return result;
        }
        sw.Write(json);
        sw.Close();
    }

    // read response
    HttpWebResponse webResponse;
    try {
        webResponse = (HttpWebResponse)webRequest.GetResponse();
    } catch (Exception ex) {
        // The remote server returned an error...
        // (400) Bad Request
        // (403) Access forbidden   (check the application pool)
        // (404) Not Found
        // (405) Method not allowed
        // (415) ...not the expected type
        // (500) Internal Server Error   (problem with IIS or unhandled error in web service)
        result.Error = ex.Message;
        return result;
    }
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
    string resultString = sr.ReadToEnd();
    sr.Close();
    responseStream.Close();
    result.JSONResponse = resultString;
    return result;
}

This method could be used as follows

public SomeCustomDataClass Getsomeinformation(int userID) {

    UserInfoClass postData = new UserInfoClass();
    postData.WebUserID = userID;
    SomeCustomDataClass result = new SomeCustomDataClass();

    string uri = URL + "SomeServices.svc/GetSomething";
    WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
    if (webReturn.Error == null) {
        //resultString = CleanJSON(resultString);
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        try {
            result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
        } catch {
            result.Error = "Error deserializing";
        }
    } else {
        result.Error = webReturn.Error;
    }
    return result;
}

Hope that helps someone



来源:https://stackoverflow.com/questions/10433551/problems-sending-and-receiving-json-between-asp-net-web-service-and-asp-net-web

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!