Web API Mapping QueryString/Form Input

If you’re using the Web API as part of the MVC4 framework, you may encounter a scenario in which you must map parameters of strange names to variables for which characters of the name would be illegal. That wasn’t very clear, so let’s do this by example. Consider part of the Facebook API:

Firstly, Facebook servers will make a single HTTP GET to your callback URL when you try to add or modify a subscription. A query string will be appended to your callback URL with the following parameters:

  • hub.mode – The string “subscribe” is passed in this parameter
  • hub.challenge – A random string
  • hub.verify_token – The verify_token value you specified when you created the subscription

Now if we wanted to use Web API to receive this data, we know that C# does not support the decimal character . existing in variable names. So, how do we bind this querystring data to variables of a different name?

After a lot of searching, I discovered that the answer is surprisingly simple – just use the FromUriAttribute:

public string Get([FromUri(Name="hub.mode")]string mode, 
    [FromUri(Name="hub.challenge")]string challenge, 
    [FromUri(Name="hub.verify_token")]string verifyToken)
    /* method body */

Works like a charm!

See also

comments powered by Disqus