Creating a Web API Controller with dynamic type

November 05, 2013 by Anuraj

.Net .Net 4.0 ASP.Net MVC Web API

Most of the time while working with Web API; we were dealing with particular model from our domain and creating GET/POST/PUT/DELETE methods that map to CRUD operations. But today I faced an issue, where I need to store some data, and I don’t have a mapping class for the same. As WebAPI doesn’t support two classes in Post action using FromBody attribute, I did it by combining FromBody and FromUri attributes, like this.

public void Post([FromBody]UserDetails userDetails, 
[FromUri]DeviceDetails deviceDetails)

And you can do post like this using fiddler.

FromBody and FromUri attributes combined

It works, but it exposes the class properties in the url, as your model class properties increases, length of the POST url also will get increase. I don’t think it is good solution. Then I found an alternate solution using dynamic type. To use dynamic type, you can modify the action method signature like this, which will accept anything.

public void Post([FromBody]dynamic dynamic)

And you can post from fiddler like this.

using FromBody attribute and dynamic type

In controller action method you can access the classes and properties like this.

public void Post([FromBody]dynamic dynamic)
{
    var userName = dynamic.UserDetails.Name.Value;
    var deviceYear = dynamic.DeviceDetails.Year.Value;
}

You can also return the dynamic type from a Web API method.

Happy Programming

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub