MyDaftQuestions MyDaftQuestions - 1 month ago 23
C# Question

Unable to connect to ASP.NET web api when I add additional parameters

I am trying understand Web Api 2 (MVC project in Visual Studio).

The method is

[HttpPost]
public string Post(int id, string e, bool o)
///code removed


Using Postman, I can query using
Post
and the path
http://localhost:62093/api/Demo/5
. This works and returns the expected value.

Now I want to add more parameters and this is where it goes wrong!

I have updated my method to

[HttpPost]
public string Post(int id, string e, bool o)


Now when I attempt to query this using (again)
Post
and the path
http://localhost:62093/api/Demo/5
I see


"Message": "The requested resource does not support http method 'POST'."


I then try to change the URL, so when I use
Post
and the new path
http://localhost:62093/api/Demo/5/a/false
I see an HTML file response of


The resource cannot be found


This has been mentioned before on Stackoverflow and from what I've understood is about the URL being 'incorrect'

Thinking this could be an issue with routes I updated mine to

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{s}/{o}",
defaults: new { id = RouteParameter.Optional, s = RouteParameter.Optional, o = RouteParameter.Optional }
);


But the same issue persists. I'm not sure what I've done wrong.

Answer Source

This is a routing issue. you have not configured your routes correctly.

First let us update the WebApiConfig.cs file

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Now with that configured I would suggest using Attribute routing

public class DemoController : ApiController {
    [HttpPost]
    [Route("api/Demo/{id:int}/{e}/{o:bool}")] //Matches POST api/Demo/5/a/false
    public IHttpActionResult Post(int id, string e, bool o) {
        return Ok();
    }
}

I would finally suggest reading up on Attribute Routing in ASP.NET Web API 2 to get a better understanding on how to properly route to your API controllers