【问题标题】:Web api routing methods with different parameter names参数名称不同的 Web api 路由方法
【发布时间】:2017-07-31 19:50:36
【问题描述】:

这个问题本可以回答一百次,但我找不到合适的资源。在 WebApi 项目(VS 提供的默认项目)中,我有如下 ValuesController。

   public string Get(int id)
    {
        return "value";
    }

    [HttpGet]
    public string FindByName(string name)
    {
        return name;
    }

    [HttpGet]
    public string FindById(int id)
    {
        return id.ToString();
    }

在 WebApiConfig.cs 中,我有以下路由映射。

 config.Routes.MapHttpRoute(
              name: "actionApiById",
              routeTemplate: "api/{controller}/{action}/{Id}",
              defaults: new { action = "FindById", Id = RouteParameter.Optional }
              );


        config.Routes.MapHttpRoute(
            name: "actionApi",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: new { name = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

现在,当我在浏览器中尝试时,只有 FindById() 操作有效。为什么其余的 api 调用返回“未找到与请求匹配的 HTTP 资源

我怎样才能让这三种方法都起作用?不使用 AttributeRouting。我缺乏 web api 的基本概念吗? (我认为是的)

【问题讨论】:

  • 你的意思是你不能调用“Get”方法?如果是这样,请分享您从客户端调用方法的方式?

标签: asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing


【解决方案1】:

AS 我们都知道 REST 是基于资源的,它通过 URL 来识别资源,因此在 REST 服务中不允许使用多个具有相同参数的方法,但在 MVC 5 Web Api 方法级别路由中存在变通方法.

以下是您可以执行此操作的示例:

[HttpGet]
[Route("api/search/FindByName/{name}")]
FindByName(string name)
{
}

[HttpGet]
[Route("api/search/FindById/{name}")]
FindById(int searchId)

注意:“search”是控制器名称。

如果需要更多说明,请告知。

【讨论】:

  • 是的,我喜欢这个解决方案,并且是我已经实现的,但我想知道这是否是好的做法?
【解决方案2】:

一般来说,您不希望像示例建议的那样为每个操作设置一个路由。随着您的应用程序的发展,这将很快失控。

还可以考虑以看起来只是 RESTfull 的方式构建您的 url 空间

所以方法将是GetByIdGetByName,然后在查询字符串中传递参数以匹配正确的操作(顺便说一句,如果他们不知道GetByIdFindById之间的区别是什么并没有什么不同,考虑只保留其中一个)。

您可以坚持使用默认路由,您的请求将如下所示:

/api/controller/345 or /api/controller?name=UserName or /api/controller?SearchId=345 (assuming search was indeed a different behavior)

然后是方法签名:

Get(int id)
{
}

[HttpGet]
FindByName(string name)
{
}

[HttpGet]
FindById(int searchId)
{
}

【讨论】:

    【解决方案3】:

    您的 actionApiById 路由也匹配 actionApi 路由,因为您的 id 是整数,请尝试使用这样的约束。

    config.Routes.MapHttpRoute(
                  name: "actionApiById",
                  routeTemplate: "api/{controller}/{action}/{Id}",
                  defaults: new { action = "FindById", Id = RouteParameter.Optional }
                  constraints: new {Id = @"\d+" }
                  );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2013-09-10
      相关资源
      最近更新 更多