Sujit.Warrier
Sujit.Warrier

Reputation: 2869

can only post to post method in asp.net core webapi

I have created non-core webapi projects to interact with mobile apps. for example If I created a controller called Data and it has a method called Search like show below. the project has been configured to send and receive json data.

[HttpPost]
public Searchresult search(SearchQuery s)
{
   // code to search
    return sr; //object of type Searchresult
}

I could send post request to this method using postman by using the following url http://localhost/api/Data/search

Similarly I can create other functions inside the controller and call them using the route '/api/[controller]/[action]'.

I could not do the same in asp.netcore web api project. The routing was controller level i.e '/api/[controller]' and every time I posted only the post method was hit. implemented int eh following way. It gets executed when I post to 'http://localhost/api/Data'

[HttpPost]
public string Post([FromBody] testclass t)
{
    return "{\"a\":\"" + t.a + "\",\"b\":\"" + t.b + "\"}";
}

The following code is never executed when I post to "http://localhost/api/Data/test"

    [HttpPost]
    public string test([FromBody] testclass t)
    {
        return "{\"a\":\""+t.a+"\",\"b\":\""+t.b+"\"}";
    }

Upvotes: 1

Views: 1564

Answers (1)

It is most likely because your controller doesn't understand difference between your routes. You need to define the routes explicitly like this:

[HttpPost("post")]
public string Post([FromBody] testclass t)
{
    return "{\"a\":\"" + t.a + "\",\"b\":\"" + t.b + "\"}";
}

[HttpPost("test")]
public string Test([FromBody] testclass t)
{
    return "{\"a\":\""+t.a+"\",\"b\":\""+t.b+"\"}";
}

And then post to them.

Upvotes: 2

Related Questions