我是Web API的新手......这是我的基本路线:
config.Routes.MapHttpRoute(
name: "Workitems",
routeTemplate: "api/{controller}/{workitemID}",
defaults: new { controller = "workitems", workitemID = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
这是我想要的:
public HttpResponseMessage Post( [FromBody] FolderModel theModel )
public HttpResponseMessage Post( [FromBody] DocumentModel theModel )
Run Code Online (Sandbox Code Playgroud)
但是,Web API没有找到我的第二个Post方法.我在这里和谷歌做了很多搜索,但没有发现任何对我有用的东西(好).我知道我可以在第二种方法中添加第二个未使用的参数 - 但这太糟糕了.如果这是正常的C#代码,那么编译器就可以知道选择b/c哪些方法具有不同的签名.但Web API不够智能.
我查看了自定义约束,但这似乎不合适.我也不能使用不同的{actions},因为它违反了我的API的RESTful约束(没有RPC,只有资源).我也不能将第二篇文章放在不同的控制器上.
我实现这一点的唯一方法是将FolderModel和DocumentModel包装在父对象中,如下所示:
public class WorkitemCreateModel
{
public DocumentModel Document { get; set; }
public FolderModel Folder { get; set; }
}
public HttpResponseMessage Post( [FromBody] WorkitemCreateModel theModel )
Run Code Online (Sandbox Code Playgroud)
然后有一个Post方法,它采用WorkitemCreateModel.但是,使用我的API的开发人员有责任必须在WorkitemCreateModel中传递它们,但它们只能传入DocumentModel对象或FolderModel对象.令人讨厌的是我的GET API可以返回DocumentModel对象或FolderModel对象.所以,将你从GET获得的对象传递给POST会很好.但这不起作用,他们必须首先将它包装在WorkitemCreateModel对象中.
还有其他建议吗?
顺便说一句:这个网站是最好的!我在这里找到了很多答案!
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public HttpResponseMessage Get( string where_name,
IndexFieldsModel index_fields = null )
public class IndexFieldsModel
{
public List<IndexFieldModel> Fields { get; set; }
}
public class IndexFieldModel
{
public string Name { get; set; }
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的API.我的问题是index_fields是名称值对的集合,它是可选的和可变长度.问题是我不知道将提前传递给我的GET方法的名称.一个示例电话是:
/api/workitems?where_name=workitem&foo=baz&bar=yo
IModelBinder是走这里的方式,还是有更简单的方法?如果是IModelBinder我如何遍历名称?我去这里看一个IModelBinder的例子:http: //www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api 但是我没有看到一种迭代名称的方法,并选择"foo"和"bar".
我尝试将index_fields更改为Dictionary<string, string>没有IModelBinding,但没有做任何事情:index_fields为null.当我在做IModelBinder并调试我的IModelBinder.BindModel例程时,如果我深入查看ModelBindingContext对象,我可以在其中看到"foo"和"bar"值System.Web.Http.ValueProviders.Providers.QueryStringValueProvider,但我不知道如何使用它.我尝试从头创建一个QueryStringValueProvider但它需要一个HttpActionContext.再一次,我没有看到迭代通过键获得"foo"和"bar"的方法.
顺便说一句:我正在使用VS2012