我創建了一個新的ASP.NET MVC4 Web Api項目。除了默認ValuesController
之外,我還添加了另一個控制器,ScenarioController
。它具有與ValuesController
完全相同的方法。但由於某種原因,它的行爲有所不同。ASP.NET MVC4 Web API控制器停留在一條路線上
/api/values/ => "value1","value2"
/api/values/1 => "value"
/api/scenario/ => "value1","value2"
/api/scenario/1 => "value1","value2"
^^^^^^^^^^^^^^^^^
should return "value"!
使用斷點,我知道,其實/api/scenario/1
獲取發送到public IEnumerable<string> Get()
,而不是預期的public string Get(int id)
。爲什麼?
僅供參考,這裏有相關的文件(這些都是原始默認mvc4-的WebAPI類,沒有修改任何東西):
的Global.asax.cs
namespace RoutingTest
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
WebApiConfig。 CS
namespace RoutingTest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
}
ValuesController.cs
namespace RoutingTest.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
}
ScenarioController.cs(是的,它在Controllers文件夾)
namespace RoutingTest.Controllers
{
public class ScenarioController : ApiController
{
// GET api/scenario
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/scenario/5
public string Get(int id)
{
return "value";
}
}
}
+1發佈最終解決這個問題的方法 – 2013-05-10 13:57:36
... aaaaaand,問題又回來了,我一直在設置新的解決方案e代碼&配置從非工作項目,並在測試第一個(新增加的)控制器時,發現只使用未參數化的Get方法相同的問題! – Noel 2013-05-10 20:30:36
welp,它有助於保持您的控制器方法參數名稱和路由配置參數名稱相同,孩子。 – Noel 2013-05-10 21:07:50