0

I have written an Asp.Net web api in which i wrote put, post,get and delete to perform crud in Sql azure database. Database and API are both live on Microsoft Azure. I am successfully able to call GET controller and fetch data in browser. When i try to post hard coded data to it via a console app, it does nothing (neither gives error nor exception). Below is the Web API controller:

public HttpResponseMessage Post([FromBody] Product prod)
    {
        try
        {
            se.Products.Add(prod);
            se.SaveChanges();

            var message = Request.CreateResponse(HttpStatusCode.Created, prod);
            message.Headers.Location = new Uri(Request.RequestUri + prod.Product_ID.ToString());
            return message;
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

Method from the client console app to send data is shown in this picture

I tried to inspect this method by putting a breakpoint at response.Response got nothing in it but showed a bad request. Here is the screenshot to it.

Kindly help me how to successfully post data to database via web api hosted on azure. Thanks :)

Ali Raza
  • 374
  • 2
  • 6
  • 21
  • GermanCH, excellent idea. Ali, the first step is to construct a HTTP post request using Postman or Fiddler4 that hits your endpoint successfully. If you are unable to do so, please also post your Product class. Once you've successfully constructed a request using one of these tools, you can examine the request that your calling method is sending and see the difference. – Rob Reagan Feb 22 '17 at 02:58
  • Thanks friend ! Should I send post request from fiddler to my actual address of API where it it hosted OR to the localhost??? I tried it for localhost where it works perfectly fine and posts data in local database. – Ali Raza Feb 25 '17 at 04:09
  • I tried to post data to address where API is hosted but I got the same response as from console client app i.e, Error: 400 Bad Request. – Ali Raza Feb 25 '17 at 04:25

2 Answers2

0

You're getting a "Bad Request" response, that means there's something wrong with the data you're sending in the request body. Check if all not nullable attributes are being sent.

Also, check the configuration for the "Content-type" header in this answer, that may be causing trouble if the data sent is allright.

I would try to use some other REST client, as Postman, to check the request's needs.

Sorry to send this as answer, I would like to just comment but I have no privileges :(

Community
  • 1
  • 1
GermanCH
  • 1
  • 3
0

Try to pass the parameter as JObject datatype to the method and typecast into your required object/class. JSON.stringify the parameter before sending to controller

 [HttpPost]
        public HttpResponseMessage Post([FromBody] JObject prod) {...}