Web api call with string parameter

I have a web api where I have 2 methods, one without a parameter and two with different types of parameters (string and int). When calling the string method, it does not work ... what am I missing here?

public class MyControllerController : ApiController { public IHttpActionResult GetInt(int id) { return Ok(1); } public IHttpActionResult GetString(string test) { return Ok("it worked"); } } 

WebApiConfig.cs:

 public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } 

My call:

/ api / MyController / MyString // Doesn't work

/ api / MyController / 1 // work

I get the following error:

The parameter dictionary contains a null entry for the parameter 'id' of a type other than nullable 'System.Int32' for the method 'System.Web.Http.IHttpActionResult GetInt (Int32)' in 'TestAngular.Controllers.MyControllerController'. The optional parameter must be a reference type, a null type, or declared as an optional parameter.

What am I missing in my request?

+6
source share
4 answers

You have to change your uri

 /api/MyController /api/MyController/string /api/MyController/1 

You do not need to specify methods.

You can look at this tutorial on asp.net for further clarification.

+7
source

Also this uri should work:

 api/MyController/GetAll api/MyController/GetString?param=string api/MyController/GetInt?param=1 

I think this is much clearer and should always work. You are using routing behavior.

See here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

+6
source

It's been a while since you posted this, but I think I have an answer. Firstly, there are two questions. First, as Pinback noted, you cannot use the same route for two different endpoints.

However, if you simply exclude the int method, you will still run into a problem. Remember: the default route looks like this: api / {controller} / {id} To bind a parameter, you need to call it "id", not "test".

Change the signature to this:

 public IHttpActionResult GetString(string id) 

and it will work. (you can also change {id} to {test} in the webapiconfig.cs file).

+2
source

Here is my solution: without changing the default route in the webapiconfig.cs file

add only the route to your string function:

 [Route("Api/MyController/GetString/{test}")] public IHttpActionResult GetString(string test) 

http: // localhost: 49609 / api / MyController / GetString / stringtest

+1
source

All Articles