19

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?

Forty-Two
  • 7,535
  • 2
  • 37
  • 54
Kremena Lalova
  • 531
  • 1
  • 4
  • 17

2 Answers2

25

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

Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
10

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

Community
  • 1
  • 1
Biser C.
  • 553
  • 5
  • 11