Tuesday, June 30, 2015

Accepting QueryString parameters in ASP.NET Web API

I was recently working on a project that wanted to send a complex serialized object to ASP.NET Web API.

Unfortunately, when you pass the serialized string to ASP.NET Web API in a RESTful manner, you get a 404 because ASP.NET Web API does not understand the RESTful Url.

However, there is a simple workaround to doing that and that is to specify the [FromUri] parameter for the ASP.NET Web API method as is outlined in this article: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
 
If you are using a primitive data type as the QueryString parameter, all of these will work:
 
http://localhost:1874/api/values?authToken=B205545C63D14E0BB17A30C05A92A120



http://localhost:1874/api/values?AuthToken=B205545C63D14E0BB17A30C05A92A120


However, the parameter name MUST MATCH the method signature!!

 



public string Get([FromUri]string authToken)
{
   return authToken;
}

If you have a method signature like this instead:

 



public string Get([FromUri]string myToken)
{
    return myToken;
}

ASP.NET Web API will INSTEAD return the DEFAULT Get method instead of the intended Get method:

 



public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Once I did this, I was able to successfully pass the object in the Query String of the Url to ASP.NET Web API and everything worked beautifully!!

No comments:

Post a Comment