I'm trying to setup an Area Route in my ASP.NET MVC application.
I'm also using the nuget package AttributeRouting, not the normal MVC register area routes thingy.
From my understanding, area routes look like this : /area/controller/method
What I'm trying to do is :- /api/search/index
which means:
Area => Api
Controller => SearchController
ActionMethod => Index
.
[RouteArea("Api")]
public class SearchController : Controller
{
[POST("Index")]
public JsonResult Index(IndexInputModel indexInputModel) { .. }
}
But that doesn't create that route. This is what it creates: /api/index
The search controller is missing.
I've had a look the docs and noticed the RoutePrefix so I tried this..
[RouteArea("Api")]
[RoutePrefix("Search")]
public class SearchController : Controller
{
[POST("Index")]
public JsonResult Index(IndexInputModel indexInputModel) { .. }
}
and that actually creates the route /api/search/index.
But why do i need to put the RoutePrefix in there? Shouldn't it be smart enough to already figure out that this is a SearchController and create the 3-segment route?
You don't need to put a RoutePrefix anywhere. It's just there as a refactoring/DRY aid. Consider:
[RouteArea("Api")]
public class SearchController : Controller
{
[POST("Search/Index")]
public ActionResult Index() { }
}
If you had a number of actions, maybe you want them all with the "Search" prefix, so you'd do:
[RouteArea("Api")]
[RoutePrefix("Search")]
public class SearchController : Controller
{
[POST("Index")]
public ActionResult Index() { }
// Other actions to prefix....
}
Shouldn't it be smart enough?
Not to be cheeky, but no. AR was never intended to read all your code for you and magically generate routes. It was intended to keep your URLs top of mind, and to do that you should see your URLs. Not that this is the best or only way of doing things, just that was my intent from the get.
The real reason why it isn't smart enough is that the concept of "Area" has nothing to do with URL. An area is a logical unit. You could expose that logical unit without any route prefix (so it would be hanging off ~/) or you could expose it off "This/Is/A/Prefix".
However, if you want it to be smart enough.... I just released v3.4, which will let you do this (if you want to; don't have to):
namespace Krome.Web.Areas.Api
{
[RouteArea]
[RoutePrefix]
public class SearchController : Controller
{
[POST]
public ActionResult Index() { }
}
}
This will yield the following route: ~/Api/Search/Index. The area comes from the last section of the controller's namespace; the route prefix comes from the controller name; and the rest of the url comes from the action name.
One more thing
If you want to get out a route area url and route prefix rat's nest for individual actions in a controller, do this:
[RouteArea("Api")]
[RoutePrefix("Search")]
public class SearchController : Controller
{
[POST("Index")]
public ActionResult Index() { }
[GET("Something")] // yields ~/Api/Search/Something
[GET("NoPrefix", IgnoreRoutePrefix = true)] // yields ~/Api/NoPrefix
[GET("NoAreaUrl", IgnoreAreaUrl = true)] // yields ~/Search/NoAreaUrl
[GET("Absolutely-Pure", IsAbsoluteUrl = true)] // yields ~/Absolutely-Pure
public ActionResult Something() {}
}
Related
I'm trying create an additional Get method on a web api but the return is 404 ( method not found ).
At my APIs before Core I was creating such methods like :
[HttpGet]
[Route("api/MyNewMethodName")]
public object MyNewMethodName(string parameter1)
{}
And for call :
myURL/api/MyNewMethodName?parameter1=somestring
At my controller definition I have :
[Produces("application/json")]
[Route("api/MyController")]
public class MyController : Controller
For the exactly some code I receive the 404 error.
What is wrong please ?
Your controller has a route defined. So for your action method, it will be the route prefix defined for the controller + the route pattern for the action method. That means, with your current code, it will work for the below request
yourBaseUrl/api/MyController/api/MyNewMethodName?parameter1=somestring
Here api/MyController part is from the route definition on the controller level and the api/MyNewMethodName part is from the action method level.
Fix the route prefix at controller or method level as needed. For instance if you want your action method to respond to /api/MyNewMethodName?parameter1=somestring. Just remove the Route decorator on the controller level.
[Produces("application/json")]
public class MyController : Controller
{
[HttpGet]
[Route("api/MyNewMethodName")]
public object MyNewMethodName(string parameter1)
{
return "Sample dummy response : "+parameter1;
}
}
Keep in mind that, removing the controller level routing might break routes to other action methods in that controller. If you want to keep the existing routes as it is (with the controller level route attributes), You may update your action method level route pattern to start with a /
[Produces("application/json")]
[Route("api/MyController")]
public class MyController : Controller
{
[HttpGet]
[Route("/api/MyNewMethodName")]
public object MyNewMethodName(string parameter1)
{
return "Some test"+parameter1;
}
[HttpGet]
[Route("SecondMethod")]
public object SecondMethod(string parameter1)
{
return "SecondMethod : "+parameter1;
}
}
[HttpGet]
[Route("api/[controller]/MyNewMethodName")]
public object MyNewMethodName(string parameter1)
{
}
Try declaring the above format, this worked for me.
I have an ASP.NET MVC app. I have seen similar question asked. However, I haven't found a good answer. Essentially, I want to use the following routes:
/admin/users
/admin/users/create
/admin/users/[someId]
/admin/roles
/admin/roles/create
/admin/roles/[someId]
I have the following file structure:
/Controllers
AdminController.cs
/Admin
UsersController.cs
RolesController.cs
/Views
/Admin
Index.cshtml
/Users
Index.cshtml
Detail.cshtml
Create.cshtml
/Roles
Index.cshtml
Create.cshtml
Detail.cshtml
When I run my app, I just get The resource cannot be found.
What am I doing wrong? I set breakpoints, but none of them are being hit. It's like the routes aren't mapping to the controllers. I'm not sure what I need to do though.
You do not need to create sub folders for this to work. Just have 2 controllers(UsersController and RolesController) and you can use attribute routing to define the custom routing pattern you want.
Assuming you have attribute routing enabled
public class UsersController : Controller
{
[Route("admin/users")]
public ActionResult Index() { // to do : Return something }
[Route("admin/users/create")]
public ActionResult Create() { // to do : Return something }
[Route("admin/users/{id}")]
public ActionResult View(int id) { // to do : Return something }
}
Or you can do the RoutePrefix on the controller level.
[RoutePrefix("admin/users")]
public class UsersController : Controller
{
[Route("")]
public ActionResult Index() { // to do : Return something }
[Route("create")]
public ActionResult Create() { // to do : Return something }
[Route("{id}")]
public ActionResult View(int id) { // to do : Return something }
}
You can do the samething for the RolesControllers as well.
You can enable attribute routing in the RegisterRoutes method in RouteConfig.cs file.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); //This line enables attribute routing
//Existing default Route definition goes here
}
You may also consider creating an "Admin" area and put your controllers inside that. Areas are the right solution if you want to logically group similar functionality.
If you do not prefer attribute routing ( why not ?) , you an define these custom route patterns in your RouteConfig. The order in you define the route matters.So make sure you define your specific routes before the default generic one.
You can also override your route tables by decorating your action methods with the RouteAttribute class.
For example:
class AdminController
{
[Route("/admin/users/create")]
public ViewResult CreateUser()
{
...
}
}
This has the advantage of separating the method name from the url component.
You can also route multiple URLs to a single method:
class AdminController
{
[Route("/admin/users/{someId:guid}")]
[Route("/admin/users/{someId:guid}/details")]
public ViewResult UserDetails(Guid someID)
{
...
}
}
As mason said, the file structure isn't important in MVC routing.
If you want to use convention (folder) based routing, you could use MvcCodeRouting to do exactly what you have specified here. It uses namespaces by default, so when you add controllers in a hierarchy, it will generate routes in the same hierarchy automatically. No need to apply the [Route] attribute everywhere and setup your routes manually.
I am working on an asp.net 5 mvc api, and I am currently working on the Accounts Controller.
since I saw in many different places that there is a convention of using /api/Tokenrouting to a login in a web api. I would like to route to that specific method without the accounts prefix, I would prefer not using a different controller, and I would prefer using Attributes over routing in Startup.cs to avoid confusion in the future.
this is what I have currently
[Route("api/[controller]")]
public class AccountsController : Controller
{
[HttpPost("login")]
public async Task<JwtToken> Token([FromBody]Credentials credentials)
{
...
}
[HttpPost]
public async Task CreateUser([FromBody] userDto)
{
...
}
}
With attribute routing you can use a tilde (~) on the Action's route attribute to override the default route of the Controller if needed:
[Route("api/[controller]")]
public class AccountsController : Controller {
[HttpPost]
[Route("~/api/token")] //routes to `/api/token`
public async Task<JwtToken> Token([FromBody]Credentials credentials) {
...
}
[HttpPost]
[Route("users")] // routes to `/api/accounts/users`
public async Task CreateUser([FromBody] userDto) {
...
}
}
For ASP.NET Core it seems that the tilde ~ symbol (see accepted answer) is not needed anymore to override the controller's route prefix – instead, the following rule applies:
Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route.
Here is an example:
[Route("foo")]
public class FooController : Controller
{
[Route("bar")] // combined with "foo" to map to route "/foo/bar"
public IActionResult Bar()
{
// ...
}
[Route("/hello/world")] // not combined; maps to route "/hello/world"
public IActionResult HelloWorld()
{
}
}
from https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
[Route("[controller]/[action]")]
public class HomeController : Controller
{
[Route("~/")]
[Route("/Home")]
[Route("~/Home/Index")]
public IActionResult Index()
{
return ControllerContext.MyDisplayRouteInfo();
}
public IActionResult About()
{
return ControllerContext.MyDisplayRouteInfo();
}
}
In the preceding code, the Index method templates must prepend / or ~/ to the route templates. Route templates applied to an action that begin with / or ~/ don't get combined with route templates applied to the controller.
I just have one quick question about what seems to have been a limitation with ASP.NET Web API Attribute Routing, but hoping I just suck at research. In my controller, I'm trying to do something like this:
public class OrdersController : ApiController
{
[HttpGet]
[Route("{apiRoot}/customers/{id:int}/orders")]
public IHttpActionResult GetCustomerOrders(int id) {...}
}
Where {apiRoot} is defined in either a configuration file.
This may not actually be necessary, but I'd like to know how to put a specific path in the route attribute without having to code a static path. Is the general idea here supposed to be that you only put text into the route path, except for your parameters which go in {}?
How about switching to using a RoutePrefix:
[MyRoutePrefix]
public class OrdersController : ApiController
{
[HttpGet]
[Route("customers/{id:int}/orders")]
public IHttpActionResult GetCustomerOrders(int id) {...}
}
public class MyRoutePrefixAttribute : RoutePrefixAttribute
{
public MyRoutePrefixAttribute()
{
Prefix = "the route prefix";
}
}
RoutePrefixAttribute isn't sealed like RouteAttribute so extending it should allow you do what you need. Assuming, of course, that all of the controllers in a single class using the same root path.
Note: I haven't had a chance to try this but given what I know of attribute routing, I don't see why it shouldn't work.
I wanted to provide some URL separation for my public/anonymous controllers and views from the admin/authenticated controllers and views. So I ended up using entirely Attribute Routing in order to take more control of my URLs. I wanted my public URLs to start with "~/Admin/etc." while my public URLs would not have any such prefix.
Public Controller (one of several)
[RoutePrefix("Home")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{ //etc. }
}
Admin Controller (one of several)
[RoutePrefix("Admin/People")]
public class PeopleController : Controller
{
[Route("Index")]
public ActionResult Index()
{ //etc. }
}
This allows me to have public URLs such as:
http://myapp/home/someaction
...and admin/authenticated URLs such as:
http://myapp/admin/people/someaction
But now I want to do some dynamic stuff in the views based on whether the user is in the Admin section or the Public section of the site. How can I access this programmatically, properly?
I know I could do something like
if (Request.Url.LocalPath.StartsWith("/Admin"))
...but it feels "hacky." I know I can access the controller and action names via
HttpContext.Current.Request.RequestContext.RouteData.Values
...but the "admin" piece isn't reflected in there, because it's just a route prefix, not an actual controller name.
So, the basic question is, how do I programmatically determine whether the currently loaded view is under the "admin" section or not?
You just need to reflect the RoutePrefixAttribute from the Controller type, and then get its Prefix value. The Controller instance is available on the ViewContext.
This example creates a handy HTML helper that wraps all of the steps into a single call.
using System;
using System.Web.Mvc;
public static class RouteHtmlHelpers
{
public static string GetRoutePrefix(this HtmlHelper helper)
{
// Get the controller type
var controllerType = helper.ViewContext.Controller.GetType();
// Get the RoutePrefix Attribute
var routePrefixAttribute = (RoutePrefixAttribute)Attribute.GetCustomAttribute(
controllerType, typeof(RoutePrefixAttribute));
// Return the prefix that is defined
return routePrefixAttribute.Prefix;
}
}
Then in your view, you just need to call the extension method to get the value of the RoutePrefixAttribute.
#Html.GetRoutePrefix() // Returns "Admin/People"