John Doe
John Doe

Reputation: 3243

Trying to understand routing for Web API2

I am new to setting up Web API methods, so I'm sure that I am butchering the routing to my action methods.

I was reading that Web API2 has attribute routing so I created:

[RoutePrefix("api/mytest")]
public class MyTestController : ApiController
{
    [Route("{id:int}")]
    [HttpGet]
    public string GetJob(int id)
    {
        return String.Format("Job-{0}", id.ToString());
    }

    [Route("/NewJob/{xmlData:string}")]
    [HttpPost]
    public HttpResponseMessage NewData(HttpRequestMessage request)
    {
          // Read in posted xml and do stuff
    }
}

In my WebApiConfig I have:

config.MapHttpAttributeRoutes();

Now the GetJob method works when I call it:

$.get('api/mytest/4')

However I do not know how to set the route for the NewData method. When I add the route attribute (see above) I get a runtime error:

The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'string'.

Updated: Changed route:

[Route("NewJob/{xmlData}")]

AJAX Call

$.post('api/mytest/NewJob/', xmlData)

Upvotes: 0

Views: 98

Answers (1)

Nazmul Hasan
Nazmul Hasan

Reputation: 10610

As the error indicates, the DefaultInlineConstraintResolver that Web API ships with does not have an inline constraint called string and it is key sensitive and you need to remove any white spaces. The default supported ones are the following:

// Type-specific constraints
{ "bool", typeof(BoolRouteConstraint) },
{ "datetime", typeof(DateTimeRouteConstraint) },
{ "decimal", typeof(DecimalRouteConstraint) },
{ "double", typeof(DoubleRouteConstraint) },
{ "float", typeof(FloatRouteConstraint) },
{ "guid", typeof(GuidRouteConstraint) },
{ "int", typeof(IntRouteConstraint) },
{ "long", typeof(LongRouteConstraint) },

// Length constraints
{ "minlength", typeof(MinLengthRouteConstraint) },
{ "maxlength", typeof(MaxLengthRouteConstraint) },
{ "length", typeof(LengthRouteConstraint) },

// Min/Max value constraints
{ "min", typeof(MinRouteConstraint) },
{ "max", typeof(MaxRouteConstraint) },
{ "range", typeof(RangeRouteConstraint) },

// Regex-based constraints
{ "alpha", typeof(AlphaRouteConstraint) },
{ "regex", typeof(RegexRouteConstraint) }

Upvotes: 2

Related Questions