MVC Core Custom Routing - c#

I am having a hard time wrapping my head around custom routing in MVC Core.
I get that I need to add something here in Startup
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
But how am I supposed to get a controller to function properly?
I basically need a data details view to pull up using a string instead of an id.
So "string url" instead of "int id".
I read some articles online but everything I tried seemed to fail.
Thanks in advance.

You should be fine by adding a route constraint, telling your code, that id will be a string (word);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id}",
defaults: null,
constraints: new {Id = #"\w+" }); /* \d+ limits to only digits*/
});
Reference: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-route-constraint-cs
Alternativley you could use AttributeRouting and decorate your controller and action methods with the appropriate Route() annotation:
[Route("api/[controller]")]
public class HomeController : Controller
{
[Route("[action]/{name}")]
public string GetSomething(string name)
{
return foo;
}
}

You use route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.

The correct solution for MVC Core is to add a constraint as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}",
defaults: null,
constraints: new { id = #"\w+" }); /* \d+ limits to only digits*/
});
In order to prevent the compile errors from happening, you need to supply a value for defaults (in this case, null), and also it should be constraints, not constraint. To prevent possible issues down the road, you should also be mindful of the case used for the id parameter.

But how am I supposed to get a controller to function properly?
I only want to underline that this is only one of various options.
Routing is used when you want to prettify the url, and manage the third slash in the url. It is the best option when the url is visible, but remember that if you are working on ajax for example you can use directly the querystring without the routing rules: controller/action?id=hello
If your need is a routing rule:
You can modify the default rule to accept also a string in the id parameter, and keep working with a method that accept an 'id'.
Add another rule that accept another parameter named for example 'code' or something that fits well for your methods that use a string research key. A
nd customize that new binding on various levels (like the default for all controllers\actions, for a single controller, ...)
You can add that custom rule also using C# Attributes in the controller.
(PROS: you have on the method the rule, so is useful to rembember, and you can import in another project the controller and all its routing rules. CONS: on large projects may be difficult understand how will interact rules that are all distributed in various files).

Related

How to route all subdomain on Net core 3.1

I want to use a different controller when users enter a subdomain. I´m using RequireHost.
How can it works this with any domain? For example I'm using domain.test just for development, but in production I have another.
Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Subdomain}/{action=Index}/{id?}").RequireHost("*.domain.test")
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
RequireHost is almost the same as adding [Host("...")] attributes everywhere, except that they only apply to that route.
Evaluation of Host rules seems to occur in HostMatcherPolicy. Which should treat "*.domain.test" as matching all subdomains, but not the domain itself. You will need to add "domain.test" if you want that to match too.
However, you do have a second route that can match everything. I suspect you will need to explicitly list the valid hosts for your default route. Or split your controllers into different areas to ensure they only match the expected rule.

Populate the Defaults RouteValueDictionary with attribute routing

I'm upgrading an ASP.NET MVC 4 project to MVC 5 and want to use attribute routing instead of convention routing. So far, so good, but I have one issue with populating the Defaults RouteValueDictionary. How can this be accomplished with attribute routing?
I am using multiple routes for the same action, each passing a different enum value to determine which type the Action is. The value of the enum will not be visible in the route directly though! This is important, otherwise I could use the value of the enum parameter in the route template.
My simplified Controller Action:
public class MyController : Controller
{
public ActionResult MyAction(MyType myTypeValue)
{
// ...
}
}
public enum MyType
{
FirstOption,
SecondOption
}
My old convention routes:
routes.Add("First", new Route("a-route", new { controller = "MyController", action = "MyAction", myTypeValue = MyType.FirstOption }));
routes.Add("Second", new Route("a-total/different-route", new { controller = "MyController", action = "MyAction", myTypeValue = MyType.Second }));
With attribute routing i was expecting to use something like this:
Route["a-route", new { myTypeValue = MyType.FirstOption }]
Route["a-total/different-route", new { myTypeValue = MyType.SecondOption }]
But unfortunately, this does not exists. I've tried to make a custom RouteAttribute that accepts an object to populate the Defaults RouteValueDictionary:
public class MyRouteAttribute : RouteFactoryAttribute
{
private RouteValueDictionary _defaults;
public Route(string template, object defaults)
:base(template)
{
_defaults = new RouteValueDictionary(defaults);
}
public override RouteValueDictionary Defaults
{
get { return _defaults; }
}
}
But this is not working since the route attribute cannot handle anonymous types compile time.
Does anyone know a way to get this working one way or another?
"Just make two different actions" is not an option here.
First of all, it is unclear why you would want to change from convention-based routing to the (less flexible) attribute-based routing, especially considering some of the features you are interested in are not supported by the latter.
But if you are insistent on changing to attribute routing just because it "looks cool", then you have a couple of options.
Option 1: Make Separate Action Methods
If you use 2 different actions and return one action from the first, you generally won't have to rewrite logic. But this is the only native support in attribute routing for setting optional parameters. An example of how you can support optional parameters with Enum can be found here.
[Route("a-route")]
public ActionResult MyAction(MyType myTypeValue = MyType.FirstOption)
{
return View("Index");
}
[Route("a-total/different-route")]
public ActionResult My2ndAction(MyType myTypeValue = MyType.SecondOption)
{
return MyAction(myTypeValue);
}
Option 2: Hack the Attribute Routing Framework
Microsoft intentionally made the attribute routing framework non-extensible by using several internal/private types to load the RouteValueCollection with the attribute routes.
You could potentially hack the attribute routing framework to provide your own logic as I have done here. This requires using Reflection, but since it runs at the start of the application rather than per-request the overall performance impact will be minimal.
But depending on your requirements, you may need to copy more of the logic from the MVC attribute routing framework to populate your routes, which may not be worth the effort. In my simple case of supporting multiple cultures it was. In your case you will need to support your own attribute types with additional parameters, which will be more challenging.
But if you need more flexibility than this, I would suggest sticking with the convention-based routing.
Attributes have limitations on which datatypes are supported as opposed to code-based solutions.
Several features including populating default route values, using constraints, and building custom routes are either much more difficult or not supported when using attribute routing.
The bottom line is, attribute routing is not the holy grail of routing. It is another routing option added in MVC 5 which can be used under a limited subset of routing scenarios of which convention-based routing is capable of. It is not and should not be viewed as a routing "upgrade" just because it happens to not have been an option until MVC 5.

Many ASP.net WebAPI routes

Just starting a project which is going to use a lot of WebAPI endpoints and had some questions about the routes. Since there are going to be many methods with different parameter names, the solution I've thought about is adding different routes with varying parameter names.
The problem is all the methods I define in various ApiController classes have the signature similar to
public string SomeMethod(string token, string id);
{
//method body
}
I'd like to have other methods with:
public string SomeMethod1(string token, string logType)
{
//method body
}
public string SomeMethod2(string token, string name)
{
//method body
} ....etc
I would like to avoid having to define every method with the parameter name as "id", so that the routes would match and would bind to the respective method in the ApiController class.
Is this an acceptable practice to add many routes in WebAPI routes config, so that varying parameters with different parameter name would bind to the correct method.
Would it affect the overall performance, if I've many routes in the config class?
Is there a better way to achieve what I'm trying to pull here?
It sounds like your main concern is the trade off between the a) need for multiple route definitions versus b) a single route with the 'id' parameter name. While I doubt the performance hit of many routes is a big deal I would lean toward a single route definition for the sake of having less code. You don't have to call the parameter 'id', but it would need to be the same. Perhaps something generic like 'argument':
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{token}/{argument}",
defaults: new { controller = "Blah", action = "SomeMethod" });

MVC Url Routing

I want to generate URL like.. It should include two IDs with employer and job including.
I am confused and have no idea about it. I have a controller Employer.
http://localhost/Employer/[employerID]/job/[jobid]
routes.MapRoute(
"EmplyerJob", // Route name
"Employer/{empid}/job/{jobid}",
new { controller = "Employer",
action = "Job" }
);
I have made a few changes to Xander's answer. I don't think you'll want to use parameters here, as this will throw off other routes to other controllers/action methods. If you use the hard-coded "Employer" and "job" strings, you will be narrowing down what routes are analyzed by this route.
Also, you can't have an optional parameter before a required parameter.

MVC Routing - Parameter names question

I'm looking for some information on Routing in MVC with C#. I'm currently very aware of the basics of routing in MVC, but what i'm looking for is somewhat difficult to find.
Effectively, what I want to find is a way of defining a single route that takes a single parameter.
The common examples I have found online is all based around the example
routes.MapRoute(
"Default",
"{controller}.mvc/{action}/{id}"
new { controller = "Default", action="Index", id=""});
By mapping this route, you can map to any action in any controller, but if you want to pass anything into the action, the method parameter must be called "id". I want to find a way around this if it's possible, so that I don't have to constantly specify routes just to use a different parameter name in my actions.
Has anyone any ideas, or found a way around this?
If you want to have a different parameter name and keep the same routing variable, use the FromUri attribute like so:
public ActionResult MyView([FromUri(Name = "id")] string parameterThatMapsToId)
{
// do stuff
}
In your routes, all you need is:
routes.MapRoute(
"Default",
"{controller}.mvc/{action}/{id}"
new { controller = "Default", action="Index", id=""});
I don't think that you can do exactly what you are asking. When MVC invokes an action it looks for parameters in routes, request params and the query string. It's always looking to match the parameter name.
Perhaps good old query string will meet your needs.
~/mycontroller/myaction/?foobar=123
will pass 123 to this action:
public ActionResult MyAction(int? foobar)
I know this is centuries ago, but hope it still helps someone. I asked the same question before. I think this is what you are looking for. An answer quoted from my question post:
"The {*pathInfo} bit is called a slug. it's basically a wildcard saying "everything after this point is stuffed into a parameter called pathInfo". Thus if you have "{resource}.axd/{*pathInfo}" and a url like this: http://blah/foo.axd/foo/bar/baz/bing then two parameters get created, one called resource, which would contain foo and one called pathInfo which contains foo/bar/baz/bing."
You can construct the routes as you like
routes.MapRoute(
"Default",
"{controller}.mvc/{action}/{param1}/{param2}/{param3}"
new { controller = "Default", action="Index", param1="", param2="", param3=""});
Also, look at this post, it contains all kind of samples in the comments section
Although you still can't use the FromUri attribute, you can however use the Route attribute, like so
[Route("~/Policy/PriorAddressDelete/{sequence}")]
public ActionResult PriorAddressDelete(int sequence)
{
Policy.RemoveScheduledPriorAddressItem(sequence);
return RedirectToAction("Information", new { id = Policy.Id });
}
Technically this adds a new route, but at least it doesn't clutter up your routeconfig. It puts the route definition right by where it's used, which I like (less hunting things down).
Remember, in order to use attribute routing, this must be in your routeconfig file above your defined routes:
routes.MapMvcAttributeRoutes();

Categories

Resources