Reputation: 33998
I have a controller which works perfectly fine:
[Authorize]
[Route("api/Version")]
public class VersionController : ApiController
{
However if I omit the Route attribute in other controllers it doesnt work, when I go to: url/api/User or Users, I get a 404
[Authorize]
public class UserController : ApiController
{
my webappi config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
}
}
my routeconfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
User Controller GetUsers
[HttpGet]
public async Task<IHttpActionResult> GetUsers()
{
Upvotes: 0
Views: 147
Reputation: 2269
You seem to be defining two different configuration classes that specify different route schemes in their methods:
WebApiConfig.Register(...)
, you have routeTemplate: "api/{controller}/{action}/{id}"
;RouteConfig.RegisterRoutes(...)
, you specified url: "{controller}/{action}/{id}"
.
Please note that these routes overlap each other, so you have to be careful when employing these configurations in your application.Regarding the VersionController
and UserController
, it seems that it is in fact the Route
attribute that is defining your route.
In VersionController
, if you specify [Route("api/Version")]
, you are correctly able to access /api/version
. If you remove this, you may be able to access /version
instead of /api/version
, or are you not? (This may help understanding what configuration - WebApiConfig
, RouteConfig
or any - is used.
Likewise, in UserController
, given that you don't specify [Route("api/User")]
, you may be able to access /user
(without the /api
prefix). Can you confirm this, please? On the other hand, if you were defining the Route
attribute, then you should be able to access api/user
.
I am assuming that you are already mapping your controllers to endpoints, since I understood that you are able to access api/version
.
This documentation is pretty good on explaining Routing in MVC projects (in this case, for .NET Core), and it explians the multiple routes approach that perhaps you are trying to achieve with WebApiConfig
and RouteConfig
.
Upvotes: 2