1

您会认为这里的所有帖子都很容易弄清楚。:| 那么这应该是一个简单的例子。注意 Web 服务是 VB,客户端是 c#。wb 服务在从 JQuery 调用时可以正常发送和接收。来自 .NET 有一个问题,如果服务要求如下所示的参数,则客户端的 getresponse 方法会收到错误 500 Internal server error

网络服务

<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

Web 客户端(设置为发送和接收 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;
    }

有没有人成功做到这一点?谢谢

4

1 回答 1

3

这是一种调用 JSON Web 服务的方法,允许开发人员发送和接收复杂数据类型。传入的对象可以是任何数据类型或类。结果是 JSON 字符串,或方法类型的任何错误消息如下所示

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;
}

该方法可以如下使用

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;
}

希望对某人有所帮助

于 2012-05-14T14:41:46.350 回答