MVC 4.5 Web API 路由不起作用? [英] MVC 4.5 Web API Routing not working?

查看:22
本文介绍了MVC 4.5 Web API 路由不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一条路线有效.

例如api/Shelves/SpaceTypes/1

第二条路线不起作用.我收到多个操作错误.

The 2nd route doesn't work. I get multiple actions error.

例如 api/Shelves/1

问)为什么?

这些是我的路线:

config.Routes.MapHttpRoute(
    "DefaultApiWithAction",
    "api/{controller}/{action}/{id}"
);

config.Routes.MapHttpRoute(
    "DefaultApiWithId",
    "api/{controller}/{id}",
    null,
    new { id = @"d+" }
);

这是我的控制器:

public HttpResponseMessage Get(int id)
{
     ...
}

[ActionName("SpaceTypes")]
public HttpResponseMessage GetSpaceTypes(int id)
{
     ...
}

推荐答案

对于 MVC 4.5,这是唯一可行的方法

目前有一个关于此的错误.

为了让您的路由正常工作,请进行以下工作

In order to get your routing to work so the following work

api/Shelves/ //Get All Shelves
api/SpaceTypes/1 //Get Shelf of id 1
api/Shelves/1/SpaceTypes/  //Get all space types for shelf 1

您需要执行以下操作.

将您的路由更改为.(注意默认操作..)

Change your routing over to. (Note the default action..)

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

在您的控制器中将基本方法更改为

In your controller change the base methods over to

[ActionName("DefaultAction")]
public string Get()
{
}

[ActionName("DefaultAction")]
public string Get(int id)
{
}

[ActionName("SpaceTypes")]
public string GetSpaceTypes(int id)
{
}

现在一切都应该按预期工作..

Now everything should work as expected..

感谢 Kip Streithorst 的完整版,完整解释

Thanks to Kip Streithorst full this, for a full explanation

这篇关于MVC 4.5 Web API 路由不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆