Custom URL in mvc .net - c#

I currently have the following url implemented:
https://example.com/controller/challenge/{params}
and would like to create a second url that accepts a different set of parameters: https://example.com/controller/v2/challenge/{params}.
I cannot seem to get the "v2" to be hardcoded into the url path. Rather, the only way I can make it work at the moment is using https://example.com/controller/challengev2/{params}
In my configuration file:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challenge", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ChallengeV2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challengev2", id = UrlParameter.Optional }
);
My controller is set up like:
public async Task<ActionResult> Challenge(string resumePath, string refid, string client_id)
{
}
[ActionName("Challengev2)]
public async Task<ActionResult> Challenge(string refid)
{
}
I have tried modifying the url when defining the route to:
routes.MapRoute(
name: "ChallengeV2",
url: "controller/v2/Challenge/{id}",
defaults: new { controller = "controller", action = "Challengev2", id = UrlParameter.Optional }
);
But this seems to throw a 404 error. Is there a step that I am missing to create that endpoint?

Switch the order you define your routes. The order plays an extremely important role.
routes.MapRoute(
name: "ChallengeV2",
url: "controller/v2/Challenge/{id}",
defaults: new { controller = "controller", action = "Challengev2" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challenge", id = UrlParameter.Optional }
);

To create a v2 route prefix, I would recommend you to use route attribute instead of route map.
Using route attribute, your code would be like this:
public class ChallengeController
{
[Route("/challenge/{resumePath}/{refid}/{client_id}")]
public async Task<ActionResult> Challenge(string resumePath, string refid, string client_id)
{
// ...
}
[Route("/v2/challenge/{refid}")]
public async Task<ActionResult> Challenge(string refid)
{
// ...
}
}

Related

set index action default action controller in asp.net mvc

I am trying to make index action is the default action in this controller when i write
http//mydomain/action
call index action > http//mydomain/case-studies
will call index action
my problem when i write the url gives me this message The resource cannot be found.
the url i write it http//mydomain/case-studiesit should be call index action but The resource cannot be found.
This is the controller
[RoutePrefix("case-studies")]
public class case_studiesController : Controller
{
// GET: CaseStudies
[Route("Index")]
public ActionResult Index()
{
return View("/views/case-studies/Index.cshtml");
}
[Route("adaep")]
public ActionResult adaep()
{
return View("/views/case-studies/pagename.cshtml");
}
}
this is my route
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 }
);
}
}
This answer worked with me to keep home route as default and make default action for every controller i changed this from [Route("Index")] to [Route("")] with the same route
[Route("")]
public ActionResult Index()
{
return View("/views/case-studies/Index.cshtml");
}
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 }
);
}
}
That route does that.the definition of the route is: if {controller} is empty use "Home" if {action} is empty use "index" if {id} has value place in the id parameter. for every url that has only the controller name, the request should go the index action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This is because your MapRoute is incorrect you're MapRoute is having a default controller of Home:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
change it to:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "case-studies", action = "Index", id = UrlParameter.Optional }
);

How to create a route for www.website.com/profile

I'm coding a website like a platform where we can access the user profile from the following URL:
www.mywebsite.com/DanielVC
The controller that has the details about the profile is the following
Controller: Perfil
Action: Perfil
I already have the following Route for all application:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
I already tried to create the following route:
routes.MapRoute(
name: "Perfil",
url: "Pages/{id}",
defaults: new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
But didn't work
Put this BEFORE (above) the default route.
routes.MapRoute(
name: "Perfil",
url: "{id}",
defaults: new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
Also, this will result in every route to be redirected to Perfil route. You must create a redirection in that action if a username is not found (e.g. mywebsite.com/randomuserthatdoesntexist) and/or other routes (mywebsite.com/contact).
EDIT
Example for your method
public class PagesController : Controller
{
public ActionResult Index(string id)
{
if (matchesOtherRoute(id))
RedirectToAction("OtherAction", "OtherController");
if (!userExists(id))
RedirectToAction("NotFoundAction", "ErrorController");
// Do other stuff here
}
}
it should be like
routes.MapRoute(
name: "Perfil",
url: "Pages/{id}",
defaults: new { controller = "Perfil", action = "Perfil", id = UrlParameter.Optional }
);

How to convert query string parameters to route in asp.net mvc 4

I have a blogging system that I'm building and I can't seem to get ASP.NET MVC to understand my route.
the route I need is /blogs/student/firstname-lastname so /blogs/student/john-doe, which routes to a blogs area, student controller's index action, which takes a string name parameter.
Here is my route
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action="Index"}
);
My controller action
public ActionResult Index(string name)
{
string[] nameparts = name.Split(new char[]{'-'});
string firstName = nameparts[0];
string lastName = nameparts[1];
if (nameparts.Length == 2 && name != null)
{
// load students blog from database
}
return RedirectToAction("Index", "Index", new { area = "Blogs" });
}
But it won't seem to resolve...it works fine with /blogs/student/?name=firstname-lastname, but not using the route I want, which is /blogs/student/firstname-lastname. Any advice on how to fix this would be greatly appreciated.
My RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action = "Index"},
constraints: new { name = #"[a-zA-Z-]+" },
namespaces: new string[] { "IAUCollege.Areas.Blogs.Controllers" }
);
routes.MapRoute(
name: "Sitemap",
url :"sitemap.xml",
defaults: new { controller = "XmlSiteMap", action = "Index", page = 0}
);
//CmsRoute is moved to Gloabal.asax
// campus maps route
routes.MapRoute(
name: "CampusMaps",
url: "locations/campusmaps",
defaults: new { controller = "CampusMaps", action = "Index", id = UrlParameter.Optional }
);
// core route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// error routes
routes.MapRoute(
name: "Error",
url: "Error/{status}",
defaults: new { controller = "Error", action = "Error404", status = UrlParameter.Optional }
);
// Add our route registration for MvcSiteMapProvider sitemaps
MvcSiteMapProvider.Web.Mvc.XmlSiteMapController.RegisterRoutes(routes);
}
}
You have to declare custom routes before the default routes. Otherwise it will be mapping to {controller}/{action}/{id}.
Global.asax typically looks like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
If you created an Area named Blogs, there is a corresponding BlogsAreaRegistration.cs file that looks like this:
public class BlogsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Blogs";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Blogs/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
Hyphens are sometimes treated like forward slashes in routes. When you are using the route blogs/students/john-doe, my guess is that it is matching the Area pattern above using blogs/students/john/doe, which would result in a 404. Add your custom route to the BlogsAreaRegistration.cs file above the default routes.
Try adding the parameter to the route:
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action="Index", name = UrlParameter.Optional}
);
Try adding a constraint for the name parameter:
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action="Index" },
constraints: new { name = #"[a-zA-Z-]+" }
);
Dashes are a bit weird in MVC at times.. because they are used to resolve underscores. I will remove this answer if this doesn't work (although.. it should).
This has the added benefit of failing to match the route if a URL such as /blogs/student/12387 is used.
EDIT:
If you have controllers with the same name.. you need to include namespaces in both of your routes in each area. It doesn't matter where the controllers are.. even if in separate areas.
Try adding the appropriate namespace to each of the routes that deal with the Student controller. Somewhat like this:
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action="Index" },
namespaces: new string[] { "Website.Areas.Blogs.Controllers" }
);
..and perhaps Website.Areas.Admin.Controllers for the one in the admin area.

ASP.NET Routing where two controller actions have the same number of parameters

We have a route config like so:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
You will notice that there are two routes that have one mandatory extra parameter. The routes About and Contact.
In our app we have two urls
www.myapp.com/Home/About/2 which works fine.
But when we navigate our browser to www.myapp.com/Home/Contact/5 we get the dreaded routing exception:
The parameters dictionary contains a null entry for parameter 'contactId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Contact(Int32)' in 'RoutingTest.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
If we change the sequence of the routing so that it looks like so:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Then the Contact url works but the About url does not.
The HomeController looks like this:
public class HomeController : Controller {
public ActionResult Index() {
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About(int aboutId) {
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact(int contactId) {
ViewBag.Message = "Your contact page.";
return View();
}
}
What this seems to imply is that two routings cannot have the same number of parameters regardless of the name of the Controller Action. If the two controller actions have a parameter with the same name, then all works fine. I know I can start doing very hacky things to work around this problem such as calling all parameters the same name or giving the actions meaningless parameters to change the number of parameters but I would actually like to know what is happening under the hood.
How do I solve this problem?
The root (no pun intended) of your issue ISN'T that routes can't have the same number of params. They can. The issue is that the routing engine will select the first route that matches the incoming request. Your routes are only different by the defaults, and pattern matching-wise they are exactly the same. So in each and every case you should be hitting the Contact route.
It looks like you are trying to have different routes based on the action. Which I can't actually see why you NEED.
You CAN use the following for that effect.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Contact",
url: "Home/Contact/{contactId}"
);
routes.MapRoute(
name: "About",
url: "Home/About/{aboutId}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
However. I HIGHLY recommend against this approach, as your "default" route would be the Contact route. This means that (under Razor) the #Html.ActionLink() and related methods will be...wrong.
Honestly, it should just work perfectly if you actually just use...
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 }
);
}
Specify controller and/or action in a route explicitly to allow routing to pick correct route:
routes.MapRoute(
name: "About",
url: "{controller}/About/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
You also can add constraints to parameters to distinguish between routes, but it looks like in your case both actions have the same integer parameter.
Couldn't you just delete your custom routes and just reuse the {id} parameter (turn {contactId} and {aboutId} into just "id" in your action code)?
public class HomeController : Controller {
public ActionResult Index() {
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About(int id) {
int aboutId = id;
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact(int id) {
int contactId = id;
ViewBag.Message = "Your contact page.";
return View();
}
}

MVC4 controller/route not working

my VisitsController:
public ActionResult Index(Visits visits, int? id)
{
....
return View(v);
}
Here is my route config
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 }
);
}
Works: http://localhost:49225/Visits
Does not work: http://localhost:49225/Visits/123
What would the custom route be (and force it to be an integer)?
You need to add a new route for that to work.
Currently, this will work:
/Visits/Index/123
I believe you need to add the following:
routes.MapRoute(
name: "VisitsDefault",
url: "Visits/{id}",
defaults: new { controller = "Visits", action = "Index",
id = UrlParameter.Optional }
);
This is assuming you have a modelbinder for Visits already.

Categories

Resources