asp.net-mvc Web API 将 Object 传递给 Get 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15571195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web API passing Object to a Get method
提问by Kremena Lalova
is there a way to pass an object as a parameter in a Get method in Web API? I have the following case:
有没有办法在 Web API 的 Get 方法中将对象作为参数传递?我有以下情况:
In my Web.API project the Get method looks like that:
在我的 Web.API 项目中,Get 方法如下所示:
public IEnumerable<ArticleMetaData> GetComponentXMLByDate(ComponentRequest request)
{
// Some logic here
return articleMeta;
}
My ComponentRequest object looks like:
我的 ComponentRequest 对象如下所示:
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
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.
在 ComponentRequest 方法中,请求为空。如果我将方法更改为接受多个字符串参数而不是对象,则它可以正常工作。
Am I missing something in my setup?
我在设置中遗漏了什么吗?
回答by Neil Thompson
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
Mike Stall 有一篇关于how-webapi-does-parameter-binding的好文章
回答by Biser C.
You need to use [FromUri]attribute.
您需要使用[FromUri]属性。
Look at the the following question. ASP.NET MVC Web Api Get Not Mapping QueryString To Strongly Typed Parameter

