How do I create a simple route in MVC3? - asp.net-mvc

I am writing a short url service in MVC3, partly as a learning tool.
When I load the url http://mysite/abc I want to redirect to an action in my controller with the following signature:
public ActionResult RedirectToLink(string shortLink)
How would I create a route in order to run this code? I have tried the following:
routes.MapRoute("Link", "{shortLink}", new { controller = "LinkController", action = "RedirectToLink" });
Alternatively, if someone can point me towards a decent primer for MVC3 that actually covers the basics rather than what's changed since the last version and would cover this scenario, I'd be much obliged.
Thanks

this is the route your want :
routes.MapRoute(
"ShortLink", // Route name
"{shortLink}", // URL with parameters
new { controller = "Link", // Parameter defaults
action = "RedirectToLink",
shortLink= UrlParameter.Optional }
);

Related

How to hide action and controller from url : asp.net mvc [duplicate]

This question already has answers here:
Routing in ASP.NET MVC, showing username in URL
(2 answers)
Closed 6 years ago.
Introduction
I am working on demo application where users can register.Users table have "username" field.There is "detail" action in "home" controller accepting parameter of string "username".
Code
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/home/Detail?username=someparam
Problem
Can i setup route like that ?
www.example.com/someparam
If its possible, then please let me know. Any kind of help or reference will be appreciated.
Thanks for your time.
That is doable if you change the way your routes are defined. Let's assume that you use dot net 4.5.2
Have a look in RouteConfig under App_Start.
A typical route definition is defined like this :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Nothing stops from changing the route to look like this :
routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
We are basically hardcoding the controller and action to be a certain value so now you could just have url/paramname and it will hit the hardcoded combination.
This being said I would not do things like this as it's against the way MVC works
MVC routes are url/controller/action. You can skip the action for generic stuff like an Index for example and your URL becomes url/controller. MVC needs to be able to identify which controller you want to hit and which action and it's best to stay within the conventions it has.
Plus, each application will typically have more than one controller, which allows a nice Separation of Concerns. Now you've hardcoded yourself ito having just one controller and action.
What you are suggesting can be done a lot easier in a webforms manner though so maybe you want to look into that.
If you define code like this
[HttpGet, Route("api/detail/{username:string}")]
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/api/Detail/someparam
So I guest you define as following, please try with your own risk!
[HttpGet, Route("/{username:string}")]
Url will be:
www.example.com/someparam

MVC 3 routing issue

Well, technically it is an ASP.net routing question but since I am using MVC 3 here we go.
I need to setup a route as follows:
http://www.mysite.com/profile/1 where 1 is the userid, however I want to hide the userid param in the query string because it is just plain ugly.
Controller is ProfileController
Action is Index
parameter is userid.
I can't seem to figure this out. I am probably thinking about it too much...
Any help would be ultra cool.
The route should be nice and simple. It needs to come before your default route handler.
routes.MapRoute(
"Profile", // Route name
"profile/{userId}", // URL with parameters
new { controller = "Profile", action = "Index" } // Parameter defaults
);

How can I achieve clean URL routing with custom user ID?

My ASP.NET MVC site allows users to register and give themselves user names, which will be unique and allow others to browse their pages with a clean URL that includes their name, like Twitter, Facebook, LinkedIn etc. do.
For example:
mysite.com/michael.guthrie
mysite.com/john
mysite.com/john/images
mysite.com/john/blog
etc.
The problem is that the first URL segment might be used for other "regular" controllers/actions, like:
mysite.com/about
mysite.com/register
So basically I seek for a routing scheme that says something like: If the first URL segment is a known controller, treat it as a controller (and parse the relevant action and parameters as usual), but if not - treat it as a user name, and pass it to a dedicated controller+action which will parse it and continue accordingly.
I don't want a solution that will enforce me to add routes for every specific controller that I have, such that after the routing module will go over all of them and won't find a match, it will get to the last one which defines a route for this special user name segment. The reason is primarily maintenance (I must remember to add a route every time I code a new controller, for example.)
I assume I can implement my own MvcRouteHandler / IRouteHandler but I feel there must be simpler solution that won't have me tweak MVC's out-of-the-box routing mechanism.
Note: I've read How to achieve nice litle USER page url like facebook or twitter? and it doesn't answer my question, it's just says that there is a URL rewriting module.
Do you know any good, elegant, clean way to achieve that?
You should have your first route be your Usesr route, with a route constraint along the lines of what I described in this answer: MVC routing question.
If your route is in the form {username}/{controller}/{id}, this route should cover all contingencies.
in the global.asax file you can map your routes
in the registerRoutes() method you can do something like this:
routes.MapRoute(
"ToonStudenten", // Route name
"{controller}/{action}/{userID}, // URL with parameters
new { controller = "Docent", action = "ToonStudenten", userID = UrlParameter.Optional} // Parameter defaults
);
I believe you can change the way your views look with this mapRouting, not entirely sure how though.. will try and search it up
You may want to take a look at this post:
MVC 3 keeping short url
You don't need to set a route for each URL. With a little help from route constraints you can do something like this:
routes.MapRoute(
"Home", // Route name
"{action}", // URL with parameters
new { controller = "Home", action = "Index" }, // Parameter defaults
new { action = "TaskA|TaskB|TaskC|etc" } //Route constraints
);
routes.MapRoute(
"Account", // Route name
"{action}", // URL with parameters
new { controller = "Account", action = "Logon" }, // Parameter defaults
new { action = "Logon|Logoff|Profile|FAQs|etc" } //Route constraints
);

Creating a specific routing entry to access a controller within an Area

I want to try and keep all my shopping cart processing within 1 controller within a separate "Area" in MVC2 project.
However, I need to expose 1 action in this controller to a URL that has been around for a long time and that URL does not include any reference to the area.
My area and controller are setup to deal with requests that look like this (Commerce is the Area):
http://www.abc.com/Commerce/Buy/Select
But the URL that I'm having to respond to is:
http://www.abc.com/quote/
Is it possible to create a one-off routing rule that would take care of this for me? I know I could create a Controller called "Quote" and sit it outside the Commerce area but I'd rather make use of routing.
Thanks.
Have you tried this?
routes.MapRoute(
"Quote", // Route name
"/Quote/{id}", // URL with parameters
new { area="Commerce", controller = "Buy", action = "Quote", id = UrlParameter.Optional } // Parameter defaults
);
Sorry, its easy as:
routes.MapRoute(
"Quote", // Route name
"Quote/", // URL with parameters
new { area = "Commerce", controller = "Buy", action = "Select" } // Parameter default
);

ASP.NET MVC: Many routes -> always only one controller

I have very simple question. My site, based on ASP.NET MVC, can have many urls, but all of them should bring to the one controller. How to do that?
I suppose I need some magic in Global.asax but I don't know how to create route that will redirect any url to the specific controller.
For example I have url /about, /product/id etc. but all of them should be really bring to the content/show where the parts of url will be recognized and the decision what information to show will be make. It's some like CMS when you cannot define routes in advance. Is this information enough?
Thanks
This sounds like a horrible idea, but, well, if you must;
routes.MapRoute(
"ReallyBadIdea",
"{*url}",
new { controller = "MyFatController", action = "MySingleAction" }
);
This routes everything to a single action in a single controller. There's also {*path} and other URL patterns should you want slightly more flexibility.
Ideally you should try and specific with your routes, for example if you have a URL that is /products/42 and you want it to go to a generic controller you should specify it explicitly like
routes.MapRoute(
"Poducts",
"products/{id}",
new { controller = "Content", action = "Show", id = UrlParameter.Optional }
);
then you would specify another route for something else like /customers/42
routes.MapRoute(
"Customers",
"customers/{id}",
new { controller = "Content", action = "Show", id = UrlParameter.Optional }
);
this may seem a little verbose, and creating a single route might seem cleaner, but the issue a single route is you will never get a 404 and will have to handle such things in code.

Resources