Reputation: 5242
I have a web api where I have 2 methods, one without parameter and two with different types of parameter (string and int). When calling the string method it doesnt 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 //Doesnt work
/api/MyController/1 //work
I get following error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetInt(Int32)' in 'TestAngular.Controllers.MyControllerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
What am I missing in my request?
Upvotes: 10
Views: 62248
Reputation: 1
You can also take string parameter in body
string body;
using (var sr = new StreamReader(Request.Body))
body = sr.ReadToEnd();
Upvotes: 0
Reputation: 41
It's been a while since you posted this, but I think I have the answer. First off, there are two issues. First, as Pinback noted, you can't use the same route for two different endpoints.
However if you just eliminate the int
method, you'll still run into the problem.
Remember: the default route looks like this: api/{controller}/{id}
In order to bind the parameter, it has to be called "id", and 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).
Upvotes: 4
Reputation: 2994
Here is my solution: without changing default route in webapiconfig.cs file
add just a route to your string function:
[Route("Api/MyController/GetString/{test}")]
public IHttpActionResult GetString(string test)
http://localhost:49609/api/MyController/GetString/stringtest
Upvotes: 9
Reputation: 2554
Also this uri's 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 use the routing behavior.
See here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
Upvotes: 8