[英]MVC5 Controller no action found using Route Attribute
I have the following MVC Controller: 我有以下MVC控制器:
[RoutePrefix("api/SystemCheck")]
public class SystemCheckController : ApiController
{
[HttpGet]
[Route("")]
[Route("EnvironmentValidate")]
[RequiresPrivilegeMVC((int)PrivilegeType.SystemCheck)]
public IEnumerable<EnvironmentValidation> Get()
{
return FilteredEnvironmentValidate();
}
I want to be able to access it these two ways: 我希望能够通过以下两种方式访问它:
When I try option 2 I get a valid response. 当我尝试选项2时,我得到一个有效的响应。 However, when I try option 1 I get: 但是,当我尝试选项1时,我得到:
{ "Message": "No HTTP resource was found that matches the request URI ' http://localhost/Perform/API/SystemCheck/EnvironmentValidate '.", "MessageDetail": "No action was found on the controller 'SystemCheck' that matches the name 'EnvironmentValidate'." {“ Message”:“未找到与请求URI'http:// localhost / Perform / API / SystemCheck / EnvironmentValidate '相匹配的HTTP资源。”,“ MessageDetail”:“在控制器'SystemCheck'上未找到与名称“ EnvironmentValidate”匹配。” } }
Is it not finding my controller action because the method name is called Get
but the route is specifying it as "EnvironmentValidate"? 是否由于方法名称称为Get
而路由将其指定为“ EnvironmentValidate”而找不到我的控制器动作?
Here is how I have configured my RouteConfig.cs: 这是我配置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") }
);
Any ideas of what I'm missing? 有什么我想念的想法吗?
Thanks, 谢谢,
It looks like you are trying to use MVC attribute routing with a WebApi controller. 您似乎正在尝试将MVC属性路由与WebApi控制器一起使用。
The routes.MapMvcAttributeRoutes()
is ignoring the attributes (since there is a mismatch between the namespace it is expecting), so only the DefaultApiGet
route is getting mapped. routes.MapMvcAttributeRoutes()
将忽略属性(因为期望的名称空间之间不匹配),因此仅映射了DefaultApiGet
路由。
You can switch ApiController
to Controller
, so that you use the MVC controller, which matches the current attribute routing you are using (assuming that the Route
attribute you are using is in the System.Web.Mvc
namespace). 您可以将ApiController
切换到Controller
,以便使用MVC控制器,该控制器与正在使用的当前属性路由匹配(假设正在使用的Route
属性在System.Web.Mvc
命名空间中)。
Or you can update the namespace to System.Web.Http
which is the WebApi namespace, and call config.MapHttpAttributeRoutes()
instead. 或者,您可以将命名空间更新为System.Web.Http
(即WebApi命名空间),然后调用config.MapHttpAttributeRoutes()
。
More instructions here https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 for setting up WebApi attribute routing. 有关设置WebApi属性路由的更多说明, 请参见https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.