Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call to web api with string parameter

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?

like image 677
MrProgram Avatar asked Nov 19 '15 08:11

MrProgram


1 Answers

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

like image 109
PinBack Avatar answered Oct 18 '22 22:10

PinBack