【问题标题】:Routing in Web Api for Get() method's overload用于 Get() 方法重载的 Web Api 中的路由
【发布时间】:2014-05-26 07:13:45
【问题描述】:

我的 Asp.Net web api 控制器中有以下代码:

class MyController:ApiController
{
    public returntype1 Get(string somevalue)
    {
    }

    public returntype2 Get(string somevalue, int id)
    {
    }
}

我的路由方法是

class RouteConfig
{
    public static void RegisterRoutes(HttpConfiguration config) 
    {
        var routes = config.Routes;  
        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{somevalue}/{id}",
            defaults: new {action = "Get", somevalue = RouetParameter.optional,id=RouteParameter.Optional }
        );
    }
}

我有第一个 Get(string somevalue) 方法的 url,例如 /api/My/get?somevalue=hello

对于第二个 Get(string somevalue, int id) 重载,例如 /api/My/get?somevalue=hello&id=1234

但我想对路由进行一些更改,以便对于第一个 Get 方法,我可以拥有像 /api/My/hello 这样的 url 对于第二个重载 Get 方法,我可以使用/api/My/hello/1234

之类的网址

【问题讨论】:

  • 您的回复将受到高度赞赏。请尝试帮助我解决这个问题。谢谢

标签: c# routing


【解决方案1】:

在 WebApiConfig.cs 中启用属性路由:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
}

你的控制器可以是这样的:

public class MyController: ApiController
{
    // Matches the route my/hello
    [Route("my/{somevalue}")]
    [HttpGet]
    public string MethodOne(string somevalue)
    {
        return somevalue;
    }

    // Matches the route my/hello/1234
    [Route("my/{somevalue}/{id}")]
    [HttpGet]
    public int MethodTwo(int id)
    {
        return id;
   }
}

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 2018-07-09
    • 1970-01-01
    • 2015-10-06
    • 2012-09-28
    • 1970-01-01
    • 2013-12-28
    • 2017-04-19
    • 1970-01-01
    相关资源
    最近更新 更多