Adolfo Perez
Adolfo Perez

Reputation: 2874

MVC5 Controller no action found using Route Attribute

I have the following MVC Controller:

[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:

  1. http://localhost/Perform/API/SystemCheck/EnvironmentValidate
  2. http://localhost/Perform/API/SystemCheck/

When I try option 2 I get a valid response. However, when I try option 1 I get:

{ "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'." }

Is it not finding my controller action because the method name is called Get but the route is specifying it as "EnvironmentValidate"?

Here is how I have configured my 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,

Upvotes: 0

Views: 1523

Answers (1)

Sunshine
Sunshine

Reputation: 449

It looks like you are trying to use MVC attribute routing with a WebApi controller.

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.

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).

Or you can update the namespace to System.Web.Http which is the WebApi namespace, and call config.MapHttpAttributeRoutes() instead.

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.

Upvotes: 2

Related Questions