WebAPI 2 Attribute routing with areas not working - c#

I'm having trouble getting WEBAPI 2 attribute routing to work. The routing scheme I'm looking for is /api/{product}/{controller}/{id-optional}, so like /api/Vision/IdCard. The controllers are in an area and are set up like this:
namespace DataServices.Controllers.Vision
{
[RoutePrefix("api/vision")]
public class IdCardController : BaseApiController
{
[System.Web.Mvc.RequireHttps]
[Route("idcard")]
public IdCardViewModel Get(HttpRequestMessage request)
{...}
Whenever I do a get to this, I get a 404. I included the namespace as the area is in it's own namespace. Are areas supported in WEBAPI attribute routing?
EDIT: WebApiConfig looks like this:
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

You need to get the HttpConfiguration instance from the GlobalConfiguration object and call the MapHttpAttributeRoutes() method from inside the RegisterArea method of the AreaRegistration.cs.
public override void RegisterArea(AreaRegistrationContext context)
{
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
//... omitted code
}
This must be done for each Area.
Finally you must in the 'WebApiConfig' remove "config.MapHttpAttributes()" method or you will get duplicate exception.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

Is the project a MVC project from start? Then I think you should remove the "ApiAreaRegistration.cs" file created when you created the area. It's found in the root of the your Api area and it will conflict with your attribute routes as it will match on a MVC (not WebApi) route like "api/{controller}/{action}/{id}" before it finds your specific routes.
Hope it helps!

Area functionality not available in Asp.Net Web API project, and its harder to maintain with custom way like Namespace based controller.
I have checked many problems with namespace based controller and routing, like single action method is accessible by namespace based routing as well as default routing.Thus custom implementation does not mitigate our requirements.
To resolve this issue we can use simple way to manage controllers routing as :
//Remove default routing registration
/*config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);*/
And use just attribute based routing only, like
[RoutePrefix("api/user/home")]
public class UserHomeController : ApiController
{
[Route]
public string Get()
{
return "Test user GET";
}
}
And for different area/module controller
[RoutePrefix("api/admin/home")]
public class AdminHomeController : ApiController
{
[Route]
public string Get()
{
return "Test admin GET";
}
}
Advantages with this approach are:
No need of custom logic like namespace based area, custom routing handler, so its better way to code.
Just need to add attribute [Route] in action to availability in API

Try play with initialization order in Application_Start
Thus:
//Config WebAPI(2) where you call config.MapHttpAttributeRoutes();
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Order is very important (if i reverse areaRegistration with WebApiConfig => WebAPI 2 attributeRouting won't work

Related

How do I not generate the default endpoints when using attribute routing?

I'm using attribute routing in a Web API controller (.NET Framework 4.5.2 - don't ask, I'm trying to get approval for time to move everything forward).
I have applied a [RoutePrefix] attribute to my ApiController.
I have two controller actions, both HttpGets. Each has a [Route] attribute applied.
I'm using Swagger to auto-generate docs. In the docs for this controller I see three endpoints listed - two for my controller actions, and another HttpGet with the bare controller route.
That is what I have is this:
[RoutePrefix("api/test/Tickets")]
public class TestTicketsController : ApiController
{
[HttpGet, Route("")]
public HttpResponseMessage GetTickets()
{
....
}
[HttpGet, Route("since")]
public HttpResponseMessage GetTicketsSince(string since)
{
....
}
}
And In the generated Swagger docs I see three endpoints:
GET api/test/Tickets
GET api/test/Tickets/since
GET api/TestTickets
This third endpoint, api/TestTickets, seems to be derived from the class name of the controller, ignored my routing attributes. And when I call it, I get an HTTP 200 with an empty body, despite not having defined an action for it.
Where is this coming from? And how can I stop it from being generated?
===
It was suggested that I remove the [HttpGet, Route("")] attribute. If I do, I get an error:
Multiple operations with path 'api/TestTickets' and method 'GET'.
It was also suggested that I include my WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new RedirectHandler((message => message.RequestUri.ToString()), "api/docs/index"));
var mediaType = new MediaTypeHeaderValue("application/json");
var formatter = new JsonMediaTypeFormatter();
formatter.SupportedMediaTypes.Clear();
formatter.SupportedMediaTypes.Add(mediaType);
config.Formatters.Clear();
config.Formatters.Add(formatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
If I comment-out the config.Routes.MapHttpRoute, the extra endpoint goes away.
Now it's just a matter of determining whether we have any controllers that expect this default endpoint to be there.
Thanks.
abdulg pointed out in a comment, rather than in an answer - default routes are configured in WebApiConfig.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Multiple actions were found that match the request But WebApiConfig is set

i'm using asp.net web api. And my problem is "Multiple actions were found that match the request" but i set route template already and in my controller i have 2 POST action
**WebApiConfig**
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.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
And this is my controller
1. [Route("{InsertRoadMap}")]
[HttpPost]
public mdRoadMapCallBack InsertRoadMap(mdEvent _mdEvent){
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
2. [Route("{UpdateRoadMap}")]
[HttpPost]
public mdRoadMapCallBack UpdateRoadMap(mdEvent _mdEvent)
{
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
What is wrong ? Please help. Thank you so much
The Route attribute doesn't seems to be implemented correctly.
Use it like this instead -
[Route("api/mycontroller/InsertRoadMap")]
[Route("api/mycontroller/UpdateRoadMap")]
Now you can browse like this - http://server/api/mycontroller/InsertRoadMap
You can also use RoutePrefix attribute at controller level so that you do not have to repeat api for every method.
[RoutePrefix("api")]
And then you can set routes like -
[Route("mycontroller/InsertRoadMap")]
[Route("mycontroller/UpdateRoadMap")]
See here and here some more information on attribute routing

Noob in ASP MVC Routing - 404 error

I'm new to API designing with VS2017 and I'm trying to make my simple API work with few SQL objects in a DB.
I have a fairly simple project which looks like this :
WebApiConfig.cs :
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Which I believe is stock so should get me where I want to.
I have some controllers based on the same principles, here's one for example :
public class UsersController : Controller
{
private APIContext db = new APIContext();
// GET: Users
public ActionResult Index()
{
return View(db.Users.ToList());
}
// GET: Users/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = db.Users.Find(id);
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
}
There are more of them, but everything has been autogenerated so I don't think I have to show them.
The problem is that when I get to localhost/api/users, I get the 404 error page :
No HTTP resource was found that matches the request URI 'http://localhost:myport/api/users'.
Same thing when I'm trying to access a specific id with /api/users/1
Can anyone point me where I should try and change things ?
I'm lost in the jungle of the config files and routes !
Thanks !
EDIT :
After some good answers, here's some more information:
I'm wondering if the issue is not somewhere else. When I'm on the localhost/api, I get a "beautiful" error page but when I try to access the /api/users/index I get an XML response with a 404 message in it. Is that a sign of another problem ?
Something to note is that the Swagger UI shows absolutely nothing.
Your Routing configuration mentions only a Controller in the template without a default Action associated with.
Multiple choices are available to you, however, I would suggest to go for a simple one as in:
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 { action = "index", id = RouteParameter.Optional }
);
}
Now the Action is part of the template, with a default value of index, you will have the following:
http://localhost:myport/api/users redirecting to UsersController.Index
http://localhost:myport/api/users/index redirecting to UsersController.Index
http://localhost:myport/api/users/details redirecting to UsersController.Details
http://localhost:myport/api/users/details/123 redirecting to UsersController.Details
Edit After a second investigation, it appears that you are using an MVC Controller rather than a WebApi Controller. While they both have the same name, they belong to different namespaces and need their own config.
In order to configure your MVC controller route, ensure to have a class as follow in your App_Start folder:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
}
Then, from the Global.asax, in Application_Start method, ensure to have the following call:
RouteConfig.RegisterRoutes(RouteTable.Routes);
as in:
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
From this point, you can now access your controller via http://localhost:myport/users.
On the other end, if you want to do an API returning data rather than views, you would need your controller to inherit from ApiController.
Use http://localhost:yourport/users/index" instead.
The URL format is always Controller/Action/Parameters.
Add a new route with {action}
config.Routes.MapHttpRoute(
name: "MyNewRoute",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { type = RouteParameter.Optional }
URL: http://localhost:myport/api/users/details/123456

404 Errors after porting .Net Core application to MVC

For supportability reasons I'm porting an application from .Net Core with ReactJs to .Net MVC.
This also uses Redux for state handling.
This seemed to be going ok but for some reason the WebAPI calls all fail with 404 errors.
I'm pretty sure the routing is correct as per the failing calls but clearly something is getting lost somewhere.
The default MVC controller that was added as an entry point works fine, it's just the ported WebAPI controllers that seem to fail.
I'm not allowed to post the entire code for commercial reasons but this is what the controller and one of the actions in question looks like:
namespace Api.Controllers
{
/// <summary>
/// Account management.
/// </summary>
[Authorize]
[System.Web.Http.RoutePrefix("api/account")]
public class AccountController : ApiController
{
// <snip>
/// <summary>
/// Current logged in account.
/// </summary>
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[System.Web.Http.Route("userinfo")]
public async Task<UserInfoViewModel> GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
var userName = User.Identity.GetUserName();
var account = new AccountRepresentation(await _context
.Accounts
.SingleOrDefaultAsync(acc => acc.Email == userName));
return new UserInfoViewModel
{
Account = account,
UserName = User.Identity.GetUserName(),
Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null,
Roles = await UserManager.GetRolesAsync(User.Identity.GetUserName())
};
}
// </snip>
}
}
(snip comments added by me)
Notice the routing attributes - it's a bit over the top as I'm trying everything, but as far as I can tell this should be ok.
However in the browser console I'm seeing this:
Failed to load resource: the server responded with a status of 404
(not found) http://localhost:49690/api/account/userinfo
The port number is correct for the default controller so unless it's different for the other controllers for some reason, this should be ok as well.
I've been playing with the RouteConfig.cs file which currently looks as follows:
namespace Api
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Api.Controllers" }
).DataTokens.Add("area", "UI");
routes.MapRoute(
name: "api",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Api.Controllers" }
).DataTokens.Add("area", "UI");
}
}
}
The WebApiConfig file looks as follows:
namespace Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API configuration and services
// Web API routes
// config.MapHttpAttributeRoutes();
// Configure Web API to use only bearer token authentication.
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
//config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
}
}
}
Application_Start() is like this:
namespace Api
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//UnityConfig.RegisterComponents();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
log4net.Config.XmlConfigurator.Configure();
}
}
}
What else could be missing or wrong that is preventing the API actions being found?
(Let me know if any other code would be helpful)
Other details:
Visual Studio version: Enterprise 2015 update 3
.NET version: 4.6.1
In .Net Core, attribute routing is now enabled by default. However, in MVC5, you are need to set it up. In your route config, add this:
routes.MapHttpAttributeRoutes();
Note that for normal MVC (i.e. not WebAPI) you need this command instead:
routes.MapMvcAttributeRoutes();
Note: MapHttpAttributeRoutes is an extension method in System.Web.Http so you will need a using System.Web.Http; statement.
if you Porting .net Core application from .net mvc you have add WebApiConfig file and register in global file. and it should be like this. First use Route Attribute because you have use Attribute routing.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

Creating a WebService inside my MVC project

I know there's another thread about WebapiConfig.cs and RouteConfig.cs, but I can assure this is a different question.
My MVC project was quite developed by the time I found out I would have to create a webservice (in the same domain) where I would grant access to one of my models (both in JSON and XML).
In order to do so, I right clicked over my Controllers and selected "add Web API 2 Controller with actions, using Entity Framework" and selected also my model class and db context.
The template was quite complete and I thought I was ready to go for the following test:
namespace MVC4GMAPS.Controllers
{
public class RestController : ApiController
{
private LocationDBContext db = new LocationDBContext();
// GET api/Rest
public IQueryable<Location> GetLocations()
{
return db.Locations;
}
etc...
Unfortunately, when I tried to access to https://localhost:44300/api/Rest I've got a 404. However, localhost:44300/Home/Index keeps working great.
I believe the problem relies on my RouteConfig.cs, because it is expecting an {action} and my RestController doesn't have any actions:
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 }
);
etc...
What can I do? Can I create simultaneously a WebapiConfig.cs file? I believe not. I hope you can help me!
Do you also have a WebApiConfig.cs? In a project which was "Web API from the start" I have this in it:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This, like the other configs, is called from Global.asax.cs:
GlobalConfiguration.Configure(WebApiConfig.Register);
That should get the routing pointed to the API controller. Otherwise, as you say, the route defined from MVC by default would be looking for an action called Rest on a controller called api which doesn't exist.

Categories