【问题标题】:Adding Routes for WebAPI in MVC 4在 MVC 4 中为 WebAPI 添加路由
【发布时间】:2012-10-29 17:02:38
【问题描述】:

我有一个 WebApi 控制器并想添加一个路由。

这是我的控制器...

        public class ExtraInformationController : ApiController
        {
            private readonly ExtraInformationRepository _extraInfoRepository = new ExtraInformationRepository();

            public ExtraInformation Get(int assetId)
            {
                return _extraInfoRepository.GetByAssetID(assetId).FirstOrDefault();
            }

        }

这是我的路线...

  routes.MapHttpRoute(
            "ExtraInformation",
            "api/ExtraInformation/{assetId}",
            new { controller = "ExtraInformation", action = "Get" }
        );

我希望能够打电话...

api/ExtraInformation/4

但我得到...

未找到与请求 URI“http://localhost:35188/api/ExtraInformation/4”匹配的 HTTP 资源。在控制器“ExtraInformation”上未找到与请求匹配的操作。

有人可以帮忙吗?

【问题讨论】:

  • 你为什么不把你的参数重命名为id
  • 如果您的操作名为Get,则无需指定“action”参数。 Web API 将根据使用的 HTTP 方法自动调用它。此外,您需要确保在默认 API 路由之前注册此路由。
  • Felipe - 因为它不是我要用于获取的主键 (id) - 它是外键 (assetId)

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


【解决方案1】:

查看您的示例,使用通用默认路由就足够了。我会把它换成这个并试一试。

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

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多