简体   繁体   中英

How to call a PUT REST WCF method from C#

we've created a REST service (which should be called with a PUT request. We've managed to call the service from a HTML page with Jquery (see below), but somehow we can not manage to do it from C#. The 'normal' webrequest just doesn't seem to work.

Should it be possible to issue a PUT request from a webrequest, and if so, how do we put the PUT data in the request?

The jquery code:

$("#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
}

Check this out using 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);
        }

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