简体   繁体   English

用于重载控制器方法的相同URL

[英]Same url for overloaded controller methods

In my web api application, I want to enable clients to make requests, using the same path, but pass different type of parameters. 在我的web api应用程序中,我想让客户端使用相同的路径发出请求,但是传递不同类型的参数。

For example: 例如:

public class MyController : ApiController
{
   [HttpDelete]
   public IHttpActionResult Delete(int id) {..}

   [HttpDelete]
   public IHttpActionResult Delete2(Guid id) {..}

   [HttpDelete]
   public IHttpActionResult Delete3(string id) {..}

}

I want the url for each method to be similar, for example: 我希望每个方法的url类似,例如:

api/MyController/1
api/MyController/abc etc..

Is this possible? 这可能吗? Iv'e tried alot of combinations with ActionName attribute and Routing configuration, but nothing seemed to work. 我尝试了很多与ActionName属性和路由配置的组合,但似乎没有任何效果。

Thanks 谢谢

You can use attribute routing for this. 您可以使用属性路由 For example: 例如:

[RoutePrefix("MyController")]
public class MyController : ApiController
{
   [HttpDelete]
   [Route("delete/{id:int}")]
   public IHttpActionResult Delete(int id) {..}

   [HttpDelete]
   [Route("delete/{id:guid}")]
   public IHttpActionResult Delete2(Guid id) {..}

   [HttpDelete]
   [Route("delete/{id:alpha}")]
   public IHttpActionResult       Delete3(string id) {..}

}

If you do this then the request url will be: 如果您这样做,那么请求网址将是:

http://yoursever/mycontroller/delete/123
http://yoursever/mycontroller/delete/abc
http://yoursever/mycontroller/delete/91c74f8f-d981-4ee1-ba36-3e9416bba202

You need to provide a Route with different parameter types for each of your methods: 您需要为每个方法提供具有不同参数类型的Route

[RoutePrefix("api/MyController")]
public class MyController : ApiController
{
   [HttpDelete]
   [Route("{id:int}", Order = 1)]
   public IHttpActionResult Delete(int id) {..}

   [HttpDelete]
   [Route("{id:guid}", Order = 2)]
   public IHttpActionResult Delete2(Guid id) {..}

   [HttpDelete]
   [Route("{id}", Order = 3)]
   public IHttpActionResult Delete3(string id) {..}

}

Of course you have to enable attribute routing if you haven't already. 当然,如果您还没有启用属性路由,则必须启用
The Order property for the Route attribute ensures that the route templates are checked in the correct order so that an int value will not match the string route. Route属性的Order属性可确保以正确的顺序检查路径模板,以使int值与字符串路径不匹配。

Yes, this is possible. 是的,这是可能的。 Try setting the route as a decoration . 尝试将路线设置为decoration

example: 例:

        [Route("DeleteThis/{id}")]
        [HttpDelete]
        public IHttpActionResult DeleteThis(int id)
        {
            return Ok();
        }

        [Route("NowDeleteThis/{name}")]
        [HttpDelete]
        public IHttpActionResult DeleteThis(string name)
        {
            return Ok();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM