Sudeep Unnikrishnan
Sudeep Unnikrishnan

Reputation: 441

How do you post to a Web API 2 OData Controller

I created a Web API 2 project and configured an OData4 controller following the steps here: Web API 2 Odata 4 Tutorial

However whenever I try and do a simple POST(with a JSON body to create an entity) using Postman I get the following error back:

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

The POST action in the controller looks like this:

public async Task<IHttpActionResult> Post(Product product)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Products.Add(product);
        await db.SaveChangesAsync();
        return Created(product);
    }

The JSON I am posting in the request body is as follows:

{  
"Id":"lewisblack",
"Name":"Lewis",
"Price":"Black",
"Category":"Category 1"
}

And I included the following headers in the request as well:

OData-Version: 4.0

OData-MaxVersion: 4.0

Content-Type: application/json

Am I missing something here?

UPDATE: Figured out the issue. I was using an incorrect URI.

Upvotes: 2

Views: 3160

Answers (2)

Sudeep Unnikrishnan
Sudeep Unnikrishnan

Reputation: 441

I incorrectly used http://localhost:/ for the POST instead of https://localhost:/Products

Upvotes: 0

NicoJuicy
NicoJuicy

Reputation: 3528

Not much information to go on:

I suspect you don't have a PostMethod on the related controller.

Otherwhise, some other things to think about:

  • OData is case sensitive
  • You are missing a property that is required
  • a datatype is wrong ( Id in the example project is an integer, it looks like a string in your project, Price should be a decimal and not a string, ...)

Whats the HTTP Response code ( if above didn't help), when you post the object. ( use a tool like fiddler). Tip, if your http response is a "bad request", then your data is probably invalid to continue in the action.

Upvotes: 1

Related Questions