christopher clark christopher clark - 28 days ago 9
C# Question

Why Is My Request Going to the Wrong Route?

My request is working, but it is not going to the right route. I don't understand why.

I am receiving my '200 ok' response when I start the project but it is at the wrong route.

I want the route

http://localhost:4047/api/[controller]
but instead
http://localhost:4047/
is working! No where am I specifying this route.


Here is the controller.


[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("api/[controller]")]
public class MenuController : ApiController
{
private IMenuRepo xMenuRepo;
public MenuController(IMenuRepo iopt)
{
xMenuRepo = iopt;
}
[HttpGet]
[Route("")]
public HttpResponseMessage GetOk()
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
}



Here is the WebApiConfig


public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
}



Here is the Route Config


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "api/{controller}",
defaults: new { controller = "Home" }
);
}


As far as I can tell,
api/Menu
should be the correct route.

Answer

Yes you are specifying the route

//GET /
[HttpGet]
[Route("")]
public HttpResponseMessage GetOk()
{
    return new HttpResponseMessage(HttpStatusCode.OK);
}

The controller needs a route prefix, while example is only specifying a controller route.

Change to:

[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api/Menu")]
public class MenuController : ApiController {
    private IMenuRepo xMenuRepo;
    public MenuController(IMenuRepo iopt) {
        xMenuRepo = iopt;
    }

    //GET api/Menu
    [HttpGet]
    [Route("")]
    public HttpResponseMessage GetOk() {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

The syntax in the OP [Route("api/[controller]")] is for asp.net-core

Source: Attribute Routing in ASP.NET Web API 2