How to get a route without the action in the URL - c#

I want my route to look like:
/product/123
I have an action GET but I don't want that in the URL, it is currently:
/product/get/123
How to get this?
Global.asax.cs
RouteConfig.RegisterRoutes(RouteTable.Routes);
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyApp.Web.Controllers" }
);
}

You can use the Route attribute to define your path like this:
[Route("product")]
public class ProductController {
[Route("{productId}"]
public ActionResult Get(int productId) {
// your code here
}
}
Which provides you the full route definition for "/product/{productId}" which is "/product/123" in your case. More details there: https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

Add this code in routes.MapRoute before the default route.
routes.MapRoute(
name: "Product",
url: "Product/{id}",
defaults: new { controller = "product", action = "get"}

Related

MVC 5 Routing issue ActionResult root

I've question about routing in MVC
i've created a simple website i defined a controller called HomeController.cs
defined my public ActionResult WebPage(int id)
the id is the Id of the page i'm displaying my route will look something like:
Current:
http://localhost:5000/Home/WebPage/1
What i want is:
http://localhost:5000/1
My current RouteConfig.cs
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 }
);
}
I've tried allot with different routes in RouteConfig.cs but im stuck can someone point me into the right direction?
I've searched on StackOverflow something similer to this but didn't find.
You should try route attribute, it may help you
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 });
}
Use attribute like this
[Route(“{id:int}”)]
public ActionResult WebPage(int id) { … }
What Felipe proposes will work, if you apply a constraint on the id value.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "WebPage",
url: "{id}",
defaults: new { controller = "Home", action = "WebPage" },
constraints: new { id = #"\d+" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
The answer
in my controller: [RoutePrefix("")] and my Method WebPage [Route("{id?}")]
[RoutePrefix("")]
public class HomeController : Controller
{
[Route("{id?}")]
public ActionResult WebPage(string id)
{
return View();
}
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "WebPage",
url: "{id}",
defaults: new { controller = "Home", action = "WebPage" }
);
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index",id = UrlParameter.Optional }
);
}
}

custom Routing from controller level in MVC5?

I am trying to defined custom routing in MVC5 like below. But when I call http://company.com/protected/Myaccount is not working. What I am doing wrong.
and also how should defined default load with http://company.com/protected. Now it is loading http://company.com/
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Protected",
url: "protected/{controller}/{action}/{id}",
defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "MyAccount", action = "Index", id = UrlParameter.Optional});
}
[RoutePrefix("Protected")]
[Route("{action=index}")]
public class MyAccountController : Controller
{
// GET: MyAccount
public ActionResult Index()
{
...
}
}
Edit: I forgot the second part of your question.
[RoutePrefix("Protected")]
public class MyAccountController : Controller
{
[Route("Index")] //Route: /Protected/Index
[Route("")] //Route : /Protected
[Route("~/")] //Route : /
public ActionResult Index()
{
return View();
}
}
With [RoutePrefix] you change the access to your controller, with [Route] you can change your access to your action (ex:parameter and order) and defined default for the controller and your app.
In this case, i delete the "Protected" route on RegisterRoute because it's not used. The RouteAttributes is another solution
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Protected",
// url: "Protected/{Controller}/{action}/{id}",
// defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional }
//);
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
In fact, attributes routing is another way to define routing, it's more flexible.

Customomized routing not working in MVC 5

My url: http:///Home/addorders //Working Fine
Need to hit like this: http:///addorders
I have added my customized route in RouteConfig: But it does not works for me
public class RouteConfig
{
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 }
);
routes.MapRoute(
"addorders", // Route name
"addorders/{id}/{str}", // URL with parameters
new { controller = "Home", action = "addorders", id = UrlParameter.Optional, str = UrlParameter.Optional },// Parameter defaults
new[] { "AngularJsExample.Controllers" }
);
}
}
MVC5 provides new feature called Attribute Routing. Instead of registering your routes in Routing Config, You can directly specify routing controller level or action level.
For example
RouteConfig.cs
using System.Web.Routing;
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();// New feature
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Home Controller code
[RoutePrefix("Test")]
[Route("{action=Index}")]// Default Route
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("HelloAbout")] //Test/Users/About
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
[Route("~/NewTest/Contact")] //To override the Route "Test" with "NewTest".... NewTest/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//[Route("home/{id?}")]
public ActionResult Emp(int id)
{
return View();
}
}
This code will change the controller and action name and also change the routing.
Add the new, more specific route before the default in the file (which determines the order it is added to the route dictionary). This is because routes are evaluated for a match to an incoming URL in order. The default MVC route is pretty general, and if route order is not carefully considered when adding additional routes to your project, the default route may inadvertently match a URL intended for a different handler.
Modified code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"addorders", // Route name
"addorders/{id}/{str}", // URL with parameters
new { controller = "Home", action = "addorders", id = UrlParameter.Optional, str = UrlParameter.Optional },// Parameter defaults
new[] { "AngularJsExample.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Routing to action getting only one ID from the URL

Im trying to make a custom router for my mvc-learning project.
I want to keep the standrard route that directs to {controller}/{action}/{id} in case of a URL like
domain.com/user/details/72
but if i get a url like this one
domain.com/2
i want to route to a specifik controller action that takes the number as an id. So i dont want the URL to specify controller and action, cause i want the url to be real short and the controller and action should always be the same.
Ive kind of made it work but i get very strange unpredictable results so i wanted to ask if im doing something very weird. Here are my routes:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new { controller = "Kombak", action = "DisplayKombak", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Try something like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new {controller = "Kombak", action = "DisplayKombak"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}
And KombakController.cs:
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class KombakController : Controller
{
public ActionResult DisplayKombak(string kombakId)
{
return View();
}
}
}
You may be able to force this behavior by adding route constraints.
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new { controller = "Kombak", action = "DisplayKombak", id = UrlParameter.Optional },
new {kombakId = #"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {controller = #"\D+" }
);
The constraint on the first route will prevent the route from matching unless the first route segment is an integer, the constraint on the second route will prevent the route from matching if the first route segment is not a string of letters.

How to customize MVC url path

I am trying to create a clean URL path to an MVC controller and I need a little assistance.
Example desired path: http://www.linkedin.com/in/alumcloud. This path is from LinkedIn and notice how it has the /in/alumcloud.
I would like for mine to read: http://www.alumcloud.com/alumcloud/somecompanyname
How would I do this with an MVC controller?
Below is the only code in my MVC controller, becuase this controller is only needed to respond to GET HTTP methods.
public class AlumCloudController : AlumCloudMvcControllerBase
{
// GET: /AlumCloud/Details/5
public ActionResult Details(string companyName)
{
return View();
}
}
--Here is my RouteConfig
public class RouteConfig
{
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 }
);
}
}
-----------------------------------2nd Attempt------------------------------------
--Route Code 2
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 }
);
routes.MapRoute(
name: "Public",
url: "ac/{companyName}",
defaults: new { controller = "AlumCloudController", action = "UserProfile" }
);
}
--Controller Code 2
public class AlumCloudController : AlumCloudMvcControllerBase
{
// GET: /AlumCloud/Details/5
public ActionResult UserProfile(string companyName)
{
return View();
}
}
--The URL
'/ac/' + options.person.CompanyName
--Snap shot of 404 error
Try adding this route above your default:
routes.MapRoute(
name: "Profile",
url: "alumcloud/{companyName}",
defaults: new { controller = "AlumCloudController", action = "Details" }
);

Categories