【问题标题】:No action was found on the controller 'User' that matches the name 'Name'在控制器“用户”上找不到与名称“名称”匹配的操作
【发布时间】:2017-01-05 14:15:19
【问题描述】:

我的控制器中有两个操作方法。

[RoutePrefix("user")]
public class UserController: ApiController
{
    [HttpGet]
    public IEnumerable<User> Get()
    {
        return new User.GetUsers();
    }

    [Route("{name}")]
    [HttpGet]
    public IEnumerable<User> GetByName(string name)
    {
        return new User.GetUsers(name);
    }
}

下面是我的路由配置文件

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{action}/{id}",
    defaults: new { controller = "user", id = RouteParameter.Optional }
    );
config.Routes.MapHttpRoute(
    name: "DefaultApiGet",
    routeTemplate: "{controller}/{id}",
    defaults: new { action = "Get", id= RouteParameter.Optional },
    constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
    );

我正在拨打以下电话

localhost/User - - Working
localhost/User/Jane -- Not working throwing error.

我不确定 API 有什么问题。

【问题讨论】:

  • 你需要在基于约定的路由之前启用属性路由config.MapHttpAttributeRoutes

标签: c# asp.net-web-api asp.net-web-api-routing


【解决方案1】:

你需要在基于约定的路由之前启用属性路由config.MapHttpAttributeRoutes()

并且还更新控制器。尽量不要在同一个控制器中混合使用基于约定的路由和属性路由

[RoutePrefix("user")]
public class UserController: ApiController
{
    //GET user
    [Route("")]
    [HttpGet]
    public IEnumerable<User> Get() { ... }

    //GET user/Jane
    [Route("{name}")]
    [HttpGet]
    public IEnumerable<User> GetByName(string name) { ... }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2011-03-06
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多