我们已经创建了一个REST服务(应该使用PUT请求来调用它。我们已经设法用Jquery从HTML页面调用了该服务(见下文),但不知何故,我们无法从C#中调用。"正常"的网络请求似乎不起作用。
是否可以从webrequest发出PUT请求?如果可以,我们如何将PUT数据放入请求中?
jquery代码:
$("#PutUpdatePassword").on("click", function () {
var data = {
userId: "9769595975",
Passold: "qwert1",
Passnew: "qwert2"
};
var json = { 'updatePassword': data };
$.ajax({
type: "PUT",
url: baseUrl + "/profile/190/updateprofile",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringifyWcf(json),
success: function () {
alert("Ok!");
},
error: function () {
alert("Fail!");
}
});
});
var request = WebRequest.Create("http://example.com/profile/190/updateprofile");
request.Method = "PUT";
request.ContentType = "application/json; charset=utf-8";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
var serializer = new JavaScriptSerializer();
var payload = serializer.Serialize(new
{
UserId = "9769595975",
Passold = "qwert1",
Passnew = "qwert2"
});
writer.Write(payload);
}
using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
// do something with the results
}
使用REST-api---检查
try
{
var pl= new payLoad(){ UserId = "9769595975",Passold = "qwert1",Passnew ="qwert2"};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(payLoad));
MemoryStream mem = new MemoryStream();
//serializing payload
ser.WriteObject(mem, pl);
string pycontent = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
HttpContent pyContentPost = new System.Net.Http.StringContent(pycontent, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsync(baseUrl+ "/profile/190/updateprofile", pyContentPost).Result;
var result = response.Content.ReadAsStringAsync().Result;
if (response.StatusCode != HttpStatusCode.OK)
{
throw new WebFaultException<string>("HttpException occured :",HttpStatusCode.InternalServerError);
}
return Convert.ToInt32(result);//return result
}
}
catch (HttpRequestException ex)
{
throw new WebFaultException<string>(string.Format("Service Exception occured : {0}", ex.Message), HttpStatusCode.BadRequest);
}