Search code examples
c#asp.netweb-servicesasp.net-web-apihttpwebrequest

Sending serialized data in Get/Post Requests


Hi I have a method in my webservice as follows

[HttpGet]
public HttpResponseMessage RegenerateReport(/*string reportObject*/)
    {
       var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StringContent("Operation completed.");
        return result;
    }

It works fine but i actually want to be able to send a serialized JSON object to this function.

Alternatively, I tried using [HttpPost] tag on this function and calling from my code as follows

var data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj));

        string _BaseUrl = ConfigurationManager.AppSettings["WebAPIBaseURL"];

        HttpWebRequest request = WebRequest.Create(string.Format("{0}{1}",
                                        _BaseUrl,
                                        "test/RegenerateReport?FileName=" + RCFileName)) as HttpWebRequest;

        // Set type to POST
        request.Method = "Post";
        request.ContentType = "application/xml";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }


        var response = (HttpWebResponse)request.GetResponse();

         var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

It returns

The requested resource does not support http method 'GET'.

Update This error is now removed as i have added both tags [HttpGet] and [HttpPost] to my web method. Now the thing is how to pass serialized object to the web service method. Thanks!


Solution

  • If you want to submit some data in web service, you should always use [HttpPost].

    I think your consumer is wrong and not doing a POST request. I typically use Microsoft.AspNet.WebApi.Client package and the sample code may look like this:

        static async Task TestApiAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:33854/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var result = await client.PostAsync("api/School", "hello", new JsonMediaTypeFormatter());
    
                result.EnsureSuccessStatusCode();
    
                // if it something returns
                string resultString = await result.Content.ReadAsAsync<string>();
                Console.WriteLine(resultString);
            }
        }
    

    Just substitute the parameters for your need (URL, type, body)