Questions about routing in Asp.net Core MVC 2 - c#

I can't wrap my mind around the routing mechanism in asp.net core MVC 2.
Here's what I have:
I already built a functioning page to add 'Materials' to a 'Application'.
The URL to call this page is:
http://localhost:33333/AddMaterial/Index/57
which uses the default route:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
Whereby 57 is the application id, so that I know what 'Application' gets the new 'Material'. The Index Method in the controller looks like this, and works like expected:
[HttpGet] public IActionResult Index(string id)
{
var model = GetModel(context, int.Parse(id));
return View("Index", model);
}
So far so good... Now here's my problem:
I want to use the same controller and view to also edit 'Materials'. But for that i'd need two parameters in Index(). I'd need:
string applicationId
string materialId
as parameters.
So I added a new route:
routes.MapRoute(
name: "whatImTryingToAchieve",
template: "{controller}/{action}/{applicationId?}/{materialId?}"
);
And of course I updated the controller:
public IActionResult Index(string applicationiId, string materialId)
{
// Do stuff with materialId etc.
// ...
return View("Index", model);
}
I know that the routing system has a specific order. So I tried defining my new route before the default route. That didn't work.
I then tried to put it after the default route, which didn't work either.
I read through a lot of information about the routing system, but I didn't seem to find the answer to my simple question:
How can I add another, specific route?
Help would be much appreciated :)
EDIT: Attribute based routing as suggested by Igors Šutovs
Controller:
[Authorize(Roles = "Admins")]
[Route("AddMaterial")]
public class AddMaterialController : Controller
{
//....
[Route("AddMaterial/{applicationId}/{otherid}")] // Nope. Nothing.
[HttpGet] public IActionResult Index(string applicationId, string otherid)
{
return View();
}
[Route("AddMaterial/Index/{applicationId}")] // Didn't work.
[Route("AddMaterial/{applicationId}")] // Didn't work either...
[HttpGet] public IActionResult Index(string applicationId)
{
return View();
}
}
So much for Attribute base routing.

I will provide my subjective opinion on the essence of the described problem. It seems that the question could be rephrased as: "What is the correct ASP.NET Core way to design routes and resolve such situations with multiple parameters?"
TLDR: use Attribute-Based Routing
This is the new type of routing which was added in ASP.MVC 5. Since then the old routing mechanism has been regarded as "Conventional-Based". ASP.NET Core currently allows mixing of both. I will provide a detailed example of how to solve the described problem using the Attribute-Based Routing only because the new approach provides the following advantages:
Route information is moved closer to controller actions, hence code is easier to understand and troubleshoot
Controller names and their method are decoupled from route names
Moving on to the solution. Let's assume that we have 2 models: Application and Material. I would create 2 distinct controllers to manage each. From your example, I understand that the relationship between these domain entities is one-to-many e.g. one Application could have many Materials. This suggests the following routes:
GET: applications/{applicationId}
GET: applications/{applicationId}/materials/{materialId}
...with a look back at principles of Restful Routing.
The ApplicationController would then look like this:
[Route("applications")]
public class ApplicationController
{
[HttpGet("{applicationId}")]
public IActionResult Index(string applicationId)
{
// return your view
}
}
While the MaterialController would look like this:
[Route("applications/{applicationId}/materials")]
public class MaterialController
{
[HttpGet("{materialId}")]
public IActionResult Index(string applicationId, string materialId)
{
// return your view
}
}
The call to UseMvc(..) extension method in Configure method of Startup.cs can now be simplified to just:
app.UseMvc();
Hope you'll find it useful!

Related

ASP.NET Core MVC Subaction in a controller

I have an Administration Controller with a Users method. And I would like to add a “new” Subaction with a new View to this method. The URL should look like this: /administration/users/new
How can I do that?
Thanks for your help!
This is really just a question about routing. Just add a method in the Administration controller and tell MVC what the route is with a Route attribute. For example:
public class AdministrationController : Controller
{
public ActionResult Users()
{
}
[Route("users/new")] //This is the important part here
public ActionResult NewUser()
{
}
}
You could also configure the routing inside your Startup.cs class, but I find it easier to do with attribute routing. See here for more information.
I guess what you mean is "Area".
So, in Asp.Net Core 2 routing, there are areas, there are controllers, there are actions and optionally parameters.
You can have routing middleware configured something like. You can specify area attribute on the contorllers.
Administrator would be area - Users would be controller and New would be action.
This should keep the code clean as this is merely using the default routing middleware.
For better understanding of Areas, please refer: https://tahirnaushad.com/2017/08/25/asp-net-core-2-0-mvc-areas/
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=dashboard}/{action=index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=home}/{action=index}/{id?}"
);
You can use several methods to do it
Routes at .net core
try attributes
[Route("users/new")]
public IActionResult New()
{
return View();
}

How to override an Action method in Mvc

I'm using a Cms for Mvc. This Cms has the following Controller:
public class OrderController : Controller
{
public ActionResult Index()
{
return View();
}
}
For customization needs, I'd like to override the behaviour of this controller and return something different when the same URL is visited by the user. What's the best approach in order to achieve this result?
I tried to inherit the Cms Controller and make the ActionResult an override, following this answer: How to override controller actionresult method in mvc3?
public class OrderController : Cms.Areas.Admin.Controllers.OrderController
{
public override ActionResult Index(Guid orderItemId)
{
// Do extra stuff
return View();
}
}
But this doesn't work. When I try to navigate "admin/order" I still enter in the Cms Controller/Action.
Any suggestion?
NOTE: The Controller I'm trying to override is in another assembly and the action is set to virtual. It's in an Area, therefore the Route is configured inside AreaRegistration.
Your request need to use OrderController instead EcommerceOrderController, take a look on your MVC routes
This seems to me to be a routing question. It doesn't matter if you override the controller if your route still points to the original. If you want a URL to invoke your action, you need to add a route with a higher priority than the one that is currently resolving to the original.

Remove controller name from URL with Attribute routing

I want to remove controller name from URL for specific Controller.
My Controller name is Product
I found some link to do this
Routing with and without controller name
MVC Routing without controller
But all the above links done in route config file. and those are affecting other controller too. I want to do it using Attribute Routing.
Can it is possible? As I want to do this for only Product controller.
I have tried to do it on action like this
[Route("Sample/{Name}")]
but it is not working.
Gabriel's answer is right, however, it can be a bit misleading since you're asking for MVC and that answer is for Web API.
In any case, what you want is to put the annotation over the class definition instead of an action method. MVC example would be like:
[RoutePrefix("SomethingOtherThanProduct")]
public class ProductController : Controller
{
public ActionResult Index()
{
...
return View();
}
}
I'm also dropping this as an answer since you may find the following article helpful: [Attribute] Routing in ASP.NET MVC 5 / WebAPI 2
Make sure you set the RoutePrefix attribute on the whole controller class, as well as using the Route attribute on the action.
[RoutePrefix("notproducts")]
public class ProductsController : ApiController
{
[Route("")]
public IEnumerable<Product> Get() { ... }
}

How to add a .Net MVC request filter to prevent action calls based on role membership?

In .Net MVC5, how would one add a request filter to prevent action calls based on role membership?
See this comment:
wouldn't it make more sense to use a request filter to prevent the
action call on the controller in the event that the current user did
not have the right role membership instead of trying to mix the auth
logic in to the business logic?
Thank you.
My best solution for this is using:
[AuthorizeAttribute]
You can place it as a normal attribute is used in c# mvc, like for ex:
[Authorize]
public ActionResult AuthenticatedUsers()
{
return View();
}
You can also use it in top of the controller like this:
[Authorize]
public class HomeController : Controller
{
}
And if you want it do be depedent on roles, you just simple give one parameter to this attribute like this:
[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
[Authorize(Users = "Betty, Johnny")]
public ActionResult SpecificUserOnly()
{
return View();
}
Here is some more detailed information for your question which I'd suggest would help you alot.
Good luck!

Fluent Security - configuring parameterized controller actions

I have done quite a bit of research and have tested both the 1.4 and 2.0 versions of the FluentSecurity libraries and I don't seem to be able to use the configuration pattern:
configuration.For<MyController>(x => x.GetCustomer())
.RequireRole(appRoles);
when my controller action requires a parameter such as:
public ActionResult GetCustomer(int customerID)
Is this type of configuration currently supported? If so, how do I implement a role requirement against an action that has a required parameter?
I was asking the same question. Currently, you can pass in default values for the parameters.
configuration
.For<HomeController>(x => x.Index(default(string)))
.DenyAnonymousAccess();
where HomeController is:
public ActionResult Index(string id)
{
return View();
}

Categories