4thSpace 4thSpace - 2 months ago 7
reST (reStructuredText) Question

Why aren't parameters binding to WebAPI app?

I'm accessing a WebAPI resource like this:

localhost/myapp/api/values?ParamOne=123&ParamTwo=testing


In ValuesController, I have this:

public class MyParams {
public int? ParamOne {get;set;}
public string ParamTwo {get;set;}
}

[HttpGet]
public HttpResponseMessage Get([FromUri]MyParams someparams) {
...
}


When I try to access the resource, I get this error:


HTTP Error 403.14 Forbidden The Web server is configured to not list
the contents of this directory


Here's the RouteConfig.cs, which is just the default:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller="Home", action="Index", id=UrlParameter.Optional}


Anyone know what I'm doing wrong?

Answer

Your WebAPI Get endpoint is expecting someparams as parameter not ParamOne and ParamTwo.

Changing your endpoint signature to the below should work with the given URL:

localhost/myapp/api/values?ParamOne=123&ParamTwo=testing

public HttpResponseMessage Get(int? ParamOne, string ParamTwo)

Updates

The route configuration above in your question is for MVC controller not WebAPI Controller. See below for WebAPI route config:

public static class WebApiConfig
    {
        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 }
            );
        }
    }

In Global.asax.cs Application_Start() method, it is registered like so:

GlobalConfiguration.Configure(WebApiConfig.Register);

NuGet packages required:

  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.WebHost

One more thing, your controller must inherit from ApiController not Controller