我有以下MVC控制器:MVC5控制器使用路由發現沒有action屬性
[RoutePrefix("api/SystemCheck")]
public class SystemCheckController : ApiController
{
[HttpGet]
[Route("")]
[Route("EnvironmentValidate")]
[RequiresPrivilegeMVC((int)PrivilegeType.SystemCheck)]
public IEnumerable<EnvironmentValidation> Get()
{
return FilteredEnvironmentValidate();
}
我希望能夠訪問它這兩種方式:
- http://localhost/Perform/API/SystemCheck/EnvironmentValidate
- http://localhost/Perform/API/SystemCheck/
當我嘗試選項2時,我得到一個有效的響應。然而,當我嘗試選項1,我得到:
{ 「消息」:「沒有HTTP資源發現匹配的請求URI‘http://localhost/Perform/API/SystemCheck/EnvironmentValidate’。」 「MessageDetail」:「沒有行動上的發現與名稱'EnvironmentValidate'匹配的控制器'SystemCheck'。「 }
它沒有找到我的控制器操作,因爲方法名稱被稱爲Get
,但路由指定它爲「EnvironmentValidate」?
這裏是我已經配置了我的RouteConfig.cs:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapHttpRoute(
name: "DefaultApiGet",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" },
constraints: new { httpMethod = new HttpMethodConstraint("GET") }
);
我失去了我的任何想法?
感謝,
我對MVC的路由不是很瞭解。但是如果我不得不猜測,我會說你的第一個選擇不是因爲你用「」設置了Route屬性,而是因爲「Get」在你的RouteConfig中被設置爲默認值。另外,如果你想使用MVC控制器作爲API,建議使用WebAPI代替(你可能有一個很好的理由不會,只是注意,如果你不知道) –
我很確定何時在MVC中映射路由,它需要第一個匹配,在這種情況下應該是他的基於屬性的路由。 –
您可能正在混合使用MVC和WebApi組件。 ApiController是一個WebApi構造,您需要使用WebApi屬性路由。每個名稱空間都有完全相同的類定義,但它們不能相互工作。 https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 – Sunshine