how to implement url rewriting similar to SO - c#

I need to implement SO like functionality on my asp.net MVC site.
For example when user go to https://stackoverflow.com/questions/xxxxxxxx
after loading the subject line is concatenated with the url and url becomes like this https://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship
Above "/rails-sql-search-through-has-one-relationship " part is added to the url.
In webforms it's simple, I could just use url rewriting. But not sure how to accomplish this in MVC
The following line is from Global.asax file
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);
the string that I need to concatenate is in my database so it fetches from there. How can I accomplish this?

This is called a slug route. One way to achieve this is to define a route with an optional slug parameter, and in the controller method check if the parameter has been provided
routes.MapRoute(
name: "Question",
url: "Question/{id}/{slug}",
defaults: new { controller = "Question", action = "Details", slug = UrlParameter.Optional }
);
Then in QuestionController (assumes an id will always be provided)
public ActionResult Details (int id, string slug)
{
if (string.IsNullOrEmpty(slug))
{
// Look up the slug in the database based on the id, but for testing
slug = "this-is-a-slug";
return RedirectToAction("Details", new { id = id, slug = slug });
}
var model = db.Questions.Find(id);
return View(model);
}

You are looking for a custom route. If you look closely, SO doesn't care about the text part of the URL. So:
http://stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship
AND
http://stackoverflow.com/questions/xxxxxxxx/
Will both work. You can easily do that with something like:
routes.MapRoute(
"Question",
"questions/{id}/{title}",
new { controller = "Question", action = "Details" });
The trick is add the "slug" at the end when you create links:
#Html.RouteLink(
"Read more.",
"Question",
new { id = question.Id, title = Slugger.ToUrl(question.Title) })

Related

Routing config issue cannot be resolved

Given this URL's
http://localhost:51095/Person // This is equivalent to this one Person/Index
http://localhost:51095/Person/Allan
I setup a route config for it as follows :
routes.MapRoute(
"Person",
"Person/{personName}",
new { controller = "Person", action = "Person", personName = UrlParameter.Optional }
)
;
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
First URL should follow the Default route and the second should follow the Person route.
This is not working because the first config seems to catch all these URL's
The first thing I'd do is remove personName = UrlParameter.Optional in the first Route. This would allow only urls that provide a personName value to access this Route. If no value is provided, it should fall through to the default Route.
But you'd want to think about the future with this strategy: if you implement new actions on that Person controller, you'd need to add a new Route for each of them. If you had a new 'Edit' action for example:
routes.MapRoute(
"Person_Edit",
"Person/Edit/{personName}",
new { controller = "Person", action = "Edit" }
)
You'd want to add these new Routes before the first one though - ordering/precedence of Routes is important.

ASP.MVC 4 - Using First QueryString Parameter & Append to Action in Url

I'd like to tidy this url if at all possible.
Curently it looks like this which is returned from an ActionResult GET
http://localhost/Controller/Action?City=SomeCity&GeoLat=00.000&GeoLong=-0.00000494
Here's what I'm trying to achieve
http://localhost/Controller/Action/SomeCity?GeoLat=00.000&GeoLong=-0.00000494
The City parameter isn't used for anything, so manually editing the first url into the second does indeed return the correct data.
I've even tried appending int the City variable to the action, not really ideal.
routes.MapRoute(
"Default",
"{controller}/{action}-{City}/",
new { controller = "House", action = "Location", City = UrlParameter.Optional }
);
Thanks!
You were almost there with the routing change. Add this code BEFORE the default route
routes.MapRoute(
"CityRoute",
"{controller}/{action}/{City}",
new { controller = "House", action = "Location" }
);
Note that I change the url format slightly and removed the optional parameter part (it's not needed)
as I correct understand, this will be solution for you:
routes.MapRoute(
name: "City",
url: "House/Location/{City}",
defaults: new { controller = "House", action = "Location" }
);
Controller:
[HttpGet]
public ActionResult Location(string City, string GeoLat, string GeoLong){ }
what is more - you have to add this before default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
at least, now you will be able to achieve GeoLat and GeoLong value, as also City parametr, in your controller method.
To get the url you're after in MVC 4 you have two options
Map a route with a city param:
routes.MapRoute(
"City",
"{controller}/{action}/{city}",
new { controller = "House", action = "Location", city = UrlParameter.Optional }
);
Rename you city param to id and use the default route mapping.
(MVC 5 introduces the RouteAttribute class that allows you to specify mappings on individual Actions.)

Add routing rules in MVC app

I am trying to write a rule to map a URL but so for I did not get the results I want. I have this rule so far:
routes.MapRoute(
"Search", // Route name
"{controller}/{action}/{product}/{page}", // URL with parameters
new { controller = "Home", action = "Search", product = UrlParameter.Optional, page = UrlParameter.Optional } // Parameter defaults
);
using this I can achieve this result so far:
localhost:8493/home/search/myproduct
localhost:8493/home/search/myproduct/2
but i want to do something like this:
localhost:8493/myproduct
so this will route to home/search/myproduct
I have tried the following but it didn't work:
routes.MapRoute(
"DirectSearch", // Route name
"{product}/{page}", // URL with parameters
new { controller = "Home", action = "Search", } // Parameter defaults
);
Is there a way to do this?
Add:
So Here i added the specific route to map to another action but it doesn't work:
routes.MapRoute(
"Tuna",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Tuna", id = UrlParameter.Optional }
);
You're close I think. This should work;
routes.MapRoute(
"Search", // Route name
"{product}/{page}", // URL with parameters
new { controller = "Home", action = "Search", product = UrlParameter.Optional, page = UrlParameter.Optional } // Parameter defaults
);
Just remember that the framework will read the route data from top to bottom and use the first one it finds that matches. So make sure the more specific routes are listed before the more general ones
Edit
Here's a link to a discussion on custom routing

MVC3 Routes with areas... a little confusion

I have an MVC3 site with 2 areas plus the common area. I also have a route specified for paginating lists of items. My Register_Routes method looks like so:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Paginate", // Route name
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Index", itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
What I've noticed (and don't understand) is if I log out from my home page, the redirect from my login page looks like
http://localhost:62695/Account/LogOn?ReturnUrl=%2fHome%2fPaginate
... and upon logging in, I end up on my home page, except with a URL of:
http://localhost:62695/Home/Paginate
I'm fairly certain at this point that I've screwed something up with the route map, but it seems right to me. What am I doing wrong?
UPDATE
per suggestion, I changed my routes to look like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Paginate", // Route name
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Index", searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
... and the home index pages do indeed seem to work properly, but now the paginates don't:
return RedirectToAction("Paginate", new { itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = string.Empty });
in a Admin\HomeController yields the URL:
http://localhost:62695/Admin/Users/Paginate?itemsPerPage=25&pageNumber=1
so I'm still doing something wrong here.
UPDATE 2
OK, this is how I got it to work the way I wanted it to:
My RegisterRoutes method now looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
null,
"{area}/{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new {area = string.Empty, controller = "Home", action="Paginate", searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{area}/{controller}/{action}/{id}", // URL with parameters
new {area = string.Empty, controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
... but this was not enough to fix the routing issues. Additionally to this, I needed to add the route to my area registrations. My AdminAreaRegistration looks like this:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
null,
"Admin/{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Paginate", searchString = UrlParameter.Optional } // Parameter defaults
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
This, in addition to changing to RedirectToRoute for my connections, made my URLs all pretty and working at the same time. All the answers helped to get to my goal, I +1'd everyone and chose the answer that got me closest to the path.
Routes are evaluated in the order they are registered. The redirects are being generated by the first route that you registered, especially since you declared default values for all of the segments. You might want to consider defining a more specific route
UPDATE
Use RedirectToRoute instead of RedirectToAction to get your desired URL generation
RedirectToRoute("Paginate", new { itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = string.Empty });
routes.MapRoute(null, // do not name your routes, it's a "magic string"
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}",
new
{
controller = "Home",
action = "Index",
searchString = UrlParameter.Optional
}
);
// instead of RedirectToAction, try RedirectToRoute, and do not use the route name
return RedirectToRoute(new
{
controller = "Home",
area = "AreaName",
itemsPerPage = SiteSettings.ItemsPerPage,
pageNumber = 1,
searchString = string.Empty,
}
);
Well, the reason you return to the URL http://localhost:62695/Home/Paginate is because when you log in you return to the URL specified, namely the ?ReturnUrl=%2fHome%2fPaginate part of http://localhost:62695/Account/LogOn?ReturnUrl=%2fHome%2fPaginate. Is that not the URL of your home page? You never specified.
It could be that the first definition takes precedence also, not sure where I heard that, so maybe if you put the default definition first it will grab that.

How can I create a friendly URL in ASP.NET MVC?

How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:
http://site/catalogue/BrowseByStyleLevel/1
The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.
For example, these two URLs will take you to the same place:
https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages
https://stackoverflow.com/questions/119323/
EDIT: The friendly part of the url is referred to as a slug.
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}/{ignoreThisBit}",
new { controller = "Home",
action = "Index",
id = "",
ignoreThisBit = ""} // Parameter defaults )
Now you can type whatever you want to at the end of your URI and the application will ignore it.
When you render the links, you need to add the "friendly" text:
<%= Html.ActionLink("Link text", "ActionName", "ControllerName",
new { id = 1234, ignoreThisBit="friendly-text-here" });
This is how I have implemented the slug URL on my application.
Note: The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute("Place", "{controller}/{action}/{id}/{slug}", new { controller = "Place", action = "Details", id = UrlParameter.Optional,slug="" });
you have a route on the global.asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""}
// Parameter defaults )
you can define your own route like :
controller is the cs class inside the the controllers folder.
you can define your id - with the name you choose.
the system will pass the value to your actionResult method.
you can read more about this step here : http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

Categories

Resources