Home > database >  Postman won't POST to ASP.Net WebAPI 2 controller, but GET works
Postman won't POST to ASP.Net WebAPI 2 controller, but GET works

Time:10-02

I can't seem to get my webapi to work in PostMan and it gives me a 404 when POSTing, but works only when using GET (even though the api specifically set to accept only POSTs! - go figure!)

Here's the controller code (that works) - NOTE: I can't use formdata as this is dotnet fw 4.72

    [Route("api/GetProfile")]
    [HttpPost]        
    public async Task<IHttpActionResult> GetProfile(string UserId)
    {
        var retval = new Profile();
        if (UserId != null)
        {
            if (await dbv.IsValidUserIdAsync(UserId))
            {
                retval = await profile_Data.GetProfileAsync(UserId);
            }
        }
        return Ok(retval);
    }

The code works fine for GET (even though it's set to accept POST!), which it shouldn't.

In PostMan, the URI is https://localhost:44371/api/GetProfile The route is 100% correct!

On the Body tab, it is set to RAW and the following JSON is inside

{"UserId" : "69d40311-f9e0-4499-82ea-959949fc34fe"}

The parameter is 100% correct! The error when attempting to POST is

   {
        "Message": "No HTTP resource was found that matches the request URI 'https://localhost:44371/api/GetProfile'.",
        "MessageDetail": "No action was found on the controller 'Accounts' that matches the request."
    }

If I put the parameters in the querystring, it works (even though the controller is set to accept POST). If I change the controller to GET and PostMan to GET (and set the parameters in params), it works.

Is PostMan not compatible with ASP.Net webapi 2.0 ? Why would GET work and POST not work? Makes no sense?

CodePudding user response:

Try to set Content-Type application/json on postman and in your controller's POST method add the attribute FromBody

[FromBody] isn't inferred for simple types such as string or int. Therefore, the [FromBody] attribute should be used for simple types when that functionality is needed.

    [Route("api/GetProfile")]
    [HttpPost]        
    public async Task<IHttpActionResult> GetProfile([FromBody] string UserId)
    {
        var retval = new Profile();
        if (UserId != null)
        {
            if (await dbv.IsValidUserIdAsync(UserId))
            {
                retval = await profile_Data.GetProfileAsync(UserId);
            }
        }
        return Ok(retval);
    }

Also consider to return CreatedAtAction or CreatedAtRoute instead of Ok

  • Related