asp.net-web-api – 基于参数类型重载Web api操作方法
发布时间:2020-05-25 03:51:56 所属栏目:asp.Net 来源:互联网
导读:有没有办法执行基于参数类型的Action方法的重载? 即可以在控制器中执行以下操作 public class MyController : ApiController{ public Foo Get(int id) { //whatever } public Foo Get(string id) { //whatever } public Foo Get(Guid id)
|
有没有办法执行基于参数类型的Action方法的重载?
public class MyController : ApiController
{
public Foo Get(int id) { //whatever }
public Foo Get(string id) { //whatever }
public Foo Get(Guid id) { //whatever }
}
如果是这样,需要对Route表进行哪些更改。 解决方法标准路由方法不能很好地支持这种情况。您可能想要使用attribute based routing,因为这样可以让您有更多的灵活性。 具体看看你可以通过类型路由的路由约束: // Type constraints
[GET("Int/{x:int}")]
[GET("Guid/{x:guid}")]
还有什么会变成一个黑客… 如果您尝试使用标准路由,您可能需要通过其名称路由到正确的操作,然后使用reg ex的约束(例如guid)路由到所需的默认操作。 控制器: public class MyController : ApiController
{
[ActionName("GetById")]
public Foo Get(int id) { //whatever }
[ActionName("GetByString")]
public Foo Get(string id) { //whatever }
[ActionName("GetByGUID")]
public Foo Get(Guid id) { //whatever }
}
路线: //Should match /api/My/1
config.Routes.MapHttpRoute(
name: "DefaultDigitApi",routeTemplate: "api/{controller}/{id}",defaults: new { action = "GetById" },constraints: new { id = @"^d+$" } // id must be digits
);
//Should match /api/My/3ead6bea-4a0a-42ae-a009-853e2243cfa3
config.Routes.MapHttpRoute(
name: "DefaultGuidApi",defaults: new { action = "GetByGUID" },constraints: new { id = @"^({{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}}{0,1})$" } // id must be guid
);
//Should match /api/My/everything else
config.Routes.MapHttpRoute(
name: "DefaultStringApi",defaults: new { action = "GetByString" }
);
更新 我通常会使用一个POST,如果做一个FromBody(可能使用与该模型的FromUri),但您的要求可以通过添加以下来满足。 对于控制器 [ActionName("GetAll")]
public string Get([FromBody]MyFooSearch model)
{
if (model != null)
{
//search criteria at api/my
}
//default for api/my
}
//should match /api/my
config.Routes.MapHttpRoute(
name: "DefaultCollection",routeTemplate: "api/{controller}",defaults: new { action = "GetAll" }
); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – ASP MVC – 默认的HTTP标头有任何常量吗?
- asp.net-mvc – 如何检查是否为浏览器启用了cookie
- asp.net-mvc – 从控制器内部使用Html.ActionLink和Url.Act
- asp.net-mvc – 如何在ASP.NET MVC路由中使用带有HttpMetho
- asp.net-vnext中的旧程序集引用错误
- asp.net-mvc-3 – 在MVC中设置403错误页面
- if-statement – 如何在VBScript for Classic-ASP中单行执行
- 为什么asp.net将页面包装在一个表单中?
- asp.net – 我可以在GoDaddy上使用NHibernate吗?
- 使用asp.net核心身份将数据存储在cookie中
推荐文章
站长推荐
- asp.net-mvc – 在asp.net mvc 3剃刀中识别html助
- 如何从asp.net中的javascript调用codebehind函数
- asp.net-mvc-4 – 我似乎没有安装SignalR与MVC4
- asp.net – DataBinding Eval到2个小数位置不显示
- asp.net-mvc-3 – .NET MVC 3自定义十进制?模型
- asp.net-mvc – 单元测试中的ViewResult.ViewNam
- asp.net – 隐藏字段vs viewstate
- asp.net – 为什么HttpUtility.UrlPathEncode标记
- asp.net-mvc-2 – 引用用TextBoxFor()创建的控件
- asp.net – 实体框架:如何解决“FOREIGN KEY约束
热点阅读
