C# create rest webservice

本文关键字:webservice rest create | 更新日期: 2023-09-27 18:14:54

我在visual studio 2010中创建了一个Rest webservice,如下所示:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DocService
{
    [WebInvoke(ResponseFormat = WebMessageFormat.Json,UriTemplate = "", BodyStyle = WebMessageBodyStyle.Wrapped)]
    public data GetCollection(Stream streamdata)
    {
    }
}

用户将发送带有json数据的请求到此服务:

var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
var jsonData = JSON.parse(JSONObject);
var request = $.ajax({
    url: "http://myIp/path/to/service",
    type: "POST",
    data: jsonData,
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

第一个问题:我如何在我的代码访问json ?现在我这样做(但json数组不能序列化正确):

StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
string resDecode = HttpUtility.UrlDecode(res);
NameValueCollection nvc = HttpUtility.ParseQueryString(resDecode);
var json = new JavaScriptSerializer().Serialize(
    nvc.AllKeys.ToDictionary(k => k, k => nvc[k])
);
输出:

res = "pCode=123456789&mCode=001&tCode=&dArr%5B0%5D%5BdCode%5D=26&dArr%5B1%5D%5BdCode%5D=27&sId=sk"
resDecode= "pCode=123456789&mCode=001&tCode=&dArr[0][dCode]=26&dArr[1][dCode]=27&sId=sk"
nvc = {pCode=123456789&mCode=001&tCode=&dArr%5b0%5d%5bdCode%5d=26&dArr%5b1%5d%5bdCode%5d=27&sId=sk}
json = "{'"pCode'":'"123456789'",'"mCode'":'"001'",'"tCode'":'"'",'"dArr[0][dCode]'":'"26'",'"dArr[1][dCode]'":'"27'",'"sId'":'"sk'"}"

第二个问题:在ajax中,请求发送后,它总是与错误和xhr.statusthrownError是0和null,但与Fiddler我可以看到json输出

C# create rest webservice

第一个问题的答案:

在c#中使用json的最佳方法是创建一个具有json对象确切名称和类型的属性的类,然后像这样反序列化json:

RequestClass reqParam = new RequestClass(); //Class with properties same as json object
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
JavaScriptSerializer js = new JavaScriptSerializer();
reqParam = js.Deserialize<RequestClass>(res);

第二个问题的答案:

我最后的javascript是这样的,工作得很好:

var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
//Delete parse line
var request = $.ajax({
    url: "http://myIp/path/to/service",
    type: "POST",
    contentType: "application/json", //Added
    data: JSONObject, // This line changed
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});