asp.net-mvc-4 - 具有不同参数名称的 Web api 路由方法

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

这个问题本可以回答一百次,但我找不到合适的资源。在 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 的基本概念? (我想是的)

最佳答案

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”为 Controller 名称。

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

关于asp.net-mvc-4 - 具有不同参数名称的 Web api 路由方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21593511/

相关文章:

c# - csharp schedule 电子邮件 razor mvc4

c# - 自定义授权中的 MVC 4.0 FormsAuthentication 和 AuthorizeAttribute

azure - 当我发布到 Azure 时,Serilog WriteTo.RollingFile 似乎会创建 500 错误代码

c# - 无法在 MVC 项目中访问 Web API 2 Controller

c# - 调用从 AJAX 返回 IHttpActionResult 的 GET 方法?

c# - 在部分 View 中创建的下拉列表在呈现时未在 View 中正确验证

ASP.NET MVC 4应用程序路由在azure中不起作用

jquery - 如何修改我的 Web API 服务器代码以添加 Access-Control-Allow-Origin' header ?

asp.net-web-api - Azure api管理身份验证链接到Web api

c# - 如何安全地处理对存储库数据的无效请求?