.NET MVC - 使用ActionName()在同一控制器中的多个GET方法

时间:2012-10-01 10:28:07

标签: .net rest routing

以下路线在我的WebApiConfig.cs中:

// routing for /profile/
config.Routes.MapHttpRoute(
    name: "profile",
    routeTemplate: "users/{userid}/profil",
    defaults: new { controller = "User", userid = RouteParameter.Optional }
);

// routing for /messages/
config.Routes.MapHttpRoute(
    name: "messages",
    routeTemplate: "users/{userid}/messages",
    defaults: new { controller = "User", userid = RouteParameter.Optional }
);

这是Controller中的相应代码:

public class UserController {

    [HttpGet]
    [ActionName("profile")]
    public HttpResponseMessage GetProfile(int userid) {}


    [HttpGet]
    [ActionName("messages")]
    public HttpResponseMessage GetMessages(int userid) {}

}

所以基本上我想在同一个控制器中有两个方法,它们都采用相同的参数,但是映射到不同的URL。 现在,我一直收到有关找到多个操作的错误 - 即使我区分了ActionName属性。

我做错了什么?我可以在同一个控制器中使用两个GET方法,获取相同的输入但是在不同的URL上调用吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您是否尝试在路由定义中专门添加操作名称?

即。

 config.Routes.MapHttpRoute(
name: "profile",
routeTemplate: "users/{userid}/profil",
defaults: new { controller = "User", action="profil", userid = RouteParameter.Optional }

);