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.
Related
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).
I have a standard set of routes, used across controllers, such as {controller}/{action}/{clientId}/{id}. All controllers are using each of these values, but each controller may use {id} in a different context.
For example, an {id} on a LabController may be "labId", and {id} on MembershipController may be "membershipId", etc. Instead of using "id" in every action method on each controller, I'd like to pass in "labId" and "membershipId" as parameters for actions in their respective controllers.
I could use [Bind(Prefix="id")] for every single action, but I was hoping there could be a way to control it at the controller level. I'm also trying to avoid multiple (nearly identical) routes for similar paths. Thanks.
EDIT: to clarify, I'm trying to bind these to parameters on my actions. Such as:
public ActionResult GetLab(int labId)
or
public ActionResult GetMembership(int membershipId)
All using the same route - just binding the {id} part as an alias for, in these cases, labId and membershipId, without having to use [Bind] every time.
You shouldn't need to bind a parameter name to the route at all. Keep in mind that the generic "id" parameter name is just a placeholder for the passed in value. So your routes become:
Lab/SomeAction/1
and
Membership/SomeAction/1
It doesn't care what the paramter name is in this case. You are thinking more in terms of query string parameters and not route parameters.
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" });
Suppose that I have a nested one to many-type hierarchy database as follows:
One Region has many Countries; each Country has many Cities; a City must belong to one and only one country.
Abstracting this information into a RDBMS is a trivial exercise, but (to my mind) the most sensible REST endpoint to return a list of countries for a given region id would be something like the following:
HTTP GET http://localhost/Region/3/Countries
By default, the .NET Web API's routing would be, at best, http://localhost/Countries/Region/3 or http://localhost/Region/Countries/3.
Is there a sensible naming-convention I should follow, or is the routing customisable enough to allow URIs to take any shape I like?
The routing should be customizable enough to get the URLs you're looking for. Assuming you want URLs in the form 'http://localhost/Region/3/Countries', you could register this custom route:
config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" });
This would dispatch requests to the 'GetCountries' action on the 'RegionController' class. You can have a regionId parameter on the action that gets model bound automatically for you from the URI.
You may want to look online for the attribute routing package for WebAPI since it may be more appropriate in your case.
Routings should be quite flexible - the question would be how you'd like to serve the data. Do you have one controller in mind or multiple?
If you had a RegionController I don't see why you couldn't configure a route:
routes.MapHttpRoute(
name: "CountryList",
routeTemplate: "{controller}/{regionId}/countries"
);
And a corresponding method:
public CountryCollection Get(int regionId)
Or am I missing something in your question? Where does your default routing come from?
Have a look at their documentation:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
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();