custom Routing from controller level in MVC5? - c#

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.

Related

how to use routes with controller and without controller

I have multi controller and Area in website. I want use url without controller for default controller name. so use this coded for route:
routes.MapRoute(
name: "WithOutController",
url: "{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
This working. But working for all controller, not only default controller. I also tried this code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "WithOutController",
url: "{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
But this code working only url with controller. I want it to work this way:
Default/Index: url(http://localhost:2470/Index)
Default/Login: url(http://localhost:2470/Login)
Panel/Index: url(http://localhost:2470/Panel/Index)
No sure how many actions your default controller need to be mapped to a URL without the default name on it. But if it is only two you can try this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultIndex",
url: "Index/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DefaultLogin",
url: "Login/{id}",
defaults: new { controller = "Default", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
Another option is to enable MapMvcAttributeRoutes and decorate your actions with the desired routes.
To enable MapMvcAttributeRoutes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "About", id = UrlParameter.Optional }
);
}
Then in your default controller you need to:
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("Login")]
public ActionResult Login()
{
return View();
}
Your default action name MUST be something different to the Route Attributes names.

Custom routing ASP.NET MVC

So I want to get my URLs to look something similar to this:
example.com, example.com/contact, example.com/sign-up, example.com/account
Instead of the default MVC way which would look like:
example.com, example.com/Home/Contact, example.com/Account/SignUp, example.com/Account/Account
All HomeController views work fine, but my AccountController doesn't.
When going to example.com/account I get an error saying:
The resource cannot be found.
This is my RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Account",
url: "{action}/{id}",
defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
);
}
And because I wanted to display the Account/SignUp view as /sign-up I added some custom code in the AccountController.
// GET: Account
public ActionResult Account()
{
return View();
}
// GET: Sign Up
[ActionName("Sign-Up")]
public ActionResult SignUp()
{
return View("SignUp");
}
Both formats /account or /account/account give me the same error from earlier.
However /about, /contact, etc. does not.
Any help is appreciated, thanks!
P.S This is my folder structure:
> Views
-> Account
--> Account.cshtml
--> SignUp.cshtml
-> Home
--> About.cshtml
--> Contact.cshtml
--> Index.cshtml
Route setup would need to be more explicit.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Account",
url: "account/{action}/{id}",
defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Maybe custom route should be before default route
Add RouteConfig.cs:
routes.MapMvcAttributeRoutes();
Add AccountController.cs as an attribute to the SignUp method
[Route("Sign-Up")]
Finally:
RouteConfig.cs
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 }
);
}
AccountController.cs
[Route("Sign-Up")]
public ActionResult SignUp()
{
ViewBag.Message = "Your application description page.";
return View();
}
Result

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 }
);
}
}

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 }
);
}
}

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