Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API passing Object to a Get method

is there a way to pass an object as a parameter in a Get method in Web API? I have the following case:

In my Web.API project the Get method looks like that:

public IEnumerable<ArticleMetaData> GetComponentXMLByDate(ComponentRequest request)
        {
           // Some logic here
            return articleMeta;
        }

My ComponentRequest object looks like:

public class ComponentRequest
    {        
        public string startdate { get; set; }
        public string enddate { get; set; }       
        public string pagenumber { get; set; }
        public string pagesize { get; set; }
    }

I am trying to call it this way:

http://mydomain.com/api/values/?startdate=121922&enddate=063020&pagenumber=2&pagesize=100

In the method ComponentRequest request is coming as null. If I change the method to accept multiple string parameters instead of the object it works fine.

Am I missing something in my setup?

like image 990
Kremena Lalova Avatar asked Mar 22 '13 13:03

Kremena Lalova


People also ask

Can we pass object as a parameter to Web API GET method?

Web API provides the necessary action methods for HTTP GET, POST, PUT, and DELETE operations. You would typically pass a single object as a parameter to the PUT and POST action methods. Note that Web API does not support passing multiple POST parameters to Web API controller methods by default.

What is FromBody and FromUri in Web API?

The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.


2 Answers

I think that

public IEnumerable<ArticleMetaData> GetComponentXMLByDate([FromUri]ComponentRequest request)
{
    // Some logic here
    return articleMeta;
}

should work.

Mike Stall has a good article on how-webapi-does-parameter-binding

like image 91
Neil Thompson Avatar answered Oct 29 '22 07:10

Neil Thompson


You need to use [FromUri] attribute.

Look at the the following question. ASP.NET MVC Web Api Get Not Mapping QueryString To Strongly Typed Parameter

like image 31
Biser C. Avatar answered Oct 29 '22 07:10

Biser C.