Pretty URL ASP.NET MVC - asp.net-mvc

How can I get pretty urls like localhost:8888/News/Example-post instead of localhost:8888/Home/Details/2
My HomeController has the following for the Details method
public ActionResult Details(int id)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyId == id select m).First();
return View(ArticleToView);

As the ASP.NET routing system is somewhat complicated, there are many ways to accomplish what you describe.
First of all, do you just want to have a pretty URL for the Details method? If so, you might consider renaming HomeController to NewsController or moving the Details method into a new NewsController class - that will automatically form the /News part of the URL. If you don't want a /Details part, you might rename your Details method Index, as that will be automatically called by /News. Finally, you need to change your int id parameter into string name.
If you want many custom URLs, you're going to have to define your own routes. Here are two ways of doing this:
1.
The easiest way I've found is to use an ASP.NET MVC Attribute-Based Route Mapper. That way, all you have to do is add an attribute on each method you want a pretty URL for and specify what URL you want.
First, you must follow a few steps to set up the attribute-based route mapping system, as outlined on that link.
After completing those steps, you must change your method to look like this:
[Url("News/{name}")]
public ActionResult Details(string name)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyName == name select m).First();
return View(ArticleToView);
}
2.
Alternatively, you can define your custom routes manually in Global.asax.cs. In your RegisterRoutes method, you can add the following in the middle:
routes.MapRoute(
"NewsDetails",
"News/{name}",
new { controller = "News", action = "Details", name = "" }
);

What I do on my sites is that I check the URL against either the Page Title or Page Stub in cases where the page titles could have the same name for instance if you have a site that posts a "Picture of the Week" you may want to use a stub instead of title as you'll have multiples named the same thing.
URLs look like this: http://mySite.com/Page/Verse-of-the-Week
Global.asax contains this:
routes.MapRoute("Pages", "{controller}/{pageID}", new { controller = "Page", action = "Index", pageID = "Home" });
PageController is this:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string pageID)
{
if (pageID == null)
{
pageID = pageRepository.HomeOrLowest();
}
var p = pageRepository.ByStub(pageID);
if (p == null) { return RedirectToAction("NotFound", "Error"); }
return View(p);
}
The repository looks like this:
private static Func<mvCmsContext, string, Page> _byStub =
CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
(from p in context.Pages
where p.pageTitle.Replace(" ", "-") == pageTitle
select p).SingleOrDefault());
public Page ByStub(string pageTitle)
{
return _byStub(context, pageTitle);
}
I hope that helps.
Edit to add duplicate handling:
private static Func<mvCmsContext, string, int> _pageExists =
CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
(from p in context.Pages
where p.pageTitle.Replace(" ", "-") == pageTitle
select p).Count());
public bool PageExists(string pageTitle)
{
return Convert.ToBoolean(_pageExists(context, pageTitle));
}
Validates like this:
IValidationErrors errors = new ValidationErrors();
if (CreateOrEdit == "Create")
{
if (pageRepository.PageExists(model.pageTitle) && !String.IsNullOrEmpty(model.pageTitle))
errors.Add("pageTitle", "A page with this title already exists. Please edit it and try again.");
}

Please check out this package I've created: https://www.nuget.org/packages/LowercaseDashedRoute/
And read the one-line configuration here: https://github.com/AtaS/lowercase-dashed-route

Related

MVC Attribute routing with Url.Action not resolving route

I cannot get #Url.Action to resolve to the url I am expecting based on the attribute route I have applied:
My action (SearchController but with [RoutePrefix("add")])
[Route("{searchTerm}/page/{page?}", Name = "NamedSearch")]
[Route("~/add")]
public ActionResult Index(string searchTerm = "", int page = 1)
{
...
}
Call to Url.Action
#Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1 })
This results in a url of
/add?searchTerm=replaceMe&page=1
I would expect
/add/replaceMe/page/1
If I type the url manually then it resolves to the correct action with the correct parameters. Why doesn't #Url.Action resolve the correct url?
Since you have a name for your pretty route definition, you may use the RouteUrl method.
#Url.RouteUrl("NamedSearch", new { searchTerm = "replaceMe", page = 1})
And since you need add in the url, you should update your route definition to include that in the url pattern.
[Route("~/add")]
[Route("~/add/{searchTerm?}/page/{page?}", Name = "NamedSearch")]
public ActionResult Index(string searchTerm = "", int page = 1)
{
// to do : return something
}
Routes are order sensitive. However, attributes are not. In fact, when using 2 Route attributes on a single action like this you may find that it works on some compiles and not on others because Reflection does not guarantee an order when analyzing custom attributes.
To ensure your routes are entered into the route table in the correct order, you need to add the Order property to each attribute.
[Route("{searchTerm}/page/{page?}", Name = "NamedSearch", Order = 1)]
[Route("~/add", Order = 2)]
public ActionResult Index(string searchTerm = "", int page = 1)
{
return View();
}
After you fix the ordering problem, the URL resolves the way you expect.
#Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1 })
// Returns "/add/replaceMe/page/1"
To return full URL use this
#Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1}, protocol: Request.Url.Scheme)
// Returns "http://yourdomain.com/add/replaceMe/page/1"
Hope this helps someone.

Asp.net mvc. Routing with trailing slash

I want to have two routes, for example:
http://localhost:1227/Product
and
http://localhost:1227/Category/
trailing slash is the only difference.
In first case I want to show information about product in other case about category. "Product" and "Category" are names of some products or categories
Is it possible to implement?
My approach:
Routes:
routes.MapRoute("category route", "{name2}", new { controller = "test", action = "GoToView2" }, new { name2 = ".*/?" });
routes.MapRoute("product route", "{name}", new { controller = "test", action = "GoToView1"});
Controller:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
return View();
}
public ActionResult GoToView1(string name)
{
// call to db to get some information about product
return View((object) name);
}
public ActionResult GoToView2(string name2)
{
// call to db to get some information about category
return View((object)name2);
}
}
Index View:
......
<br/>
Show proudct
<br/>
Show category
......
But I see that only "GoToView2" is called for two link.
Any ideas how to fix it?
Thanks,
Why would one wants to do that? in your case you have to completely different controller, namely Product and Category and two different action, and even if we could implement the same URL to call different action based on slash, it would be a code smell(bad design), in your case you can simply call TestController/GoToView1 and TestController/GoToView2, if this is not the case, tell us exactly what problem you are trying to solve, maybe there would be a better approach.

Redirect with ASP.NET MVC MapRoute

On my site, I have moved some images from one folder to another.
Now, when I receive a request for old images '/old_folder/images/*' I want to make a permanent redirect to new folder with these images '/new_folder/images/*'
For example:
/old_folder/images/image1.png => /new_folder/images/image1.png
/old_folder/images/image2.jpg => /new_folder/images/image2.jpg
I have added a simple redirect controller
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent(path);
}
}
Now I need to setup proper routing, but I don't know how to pass the path part to the path parameter.
routes.MapRoute("ImagesFix", "/old_folder/images/{*pathInfo}", new { controller = "Redirect", action = "Index", path="/upload/images/????" });
Thanks
I would do in next way
routes.MapRoute("ImagesFix", "/old_folder/images/{path}", new { controller = "Redirect", action = "Index" });
and in controller like that
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent("/upload/images/" + path);
}
}
first download and install RouteMagic package from this link , then redirect your old address to the new address Like the below code :
var NewPath = routes.MapRoute("new", "new_folder/images/{controller}/{action}");
var OldPath = routes.MapRoute("new", "old_folder/images/{controller}/{action}");
routes.Redirect(OldPath ).To(NewPath );
for more information please check out the following link
Redirecting Routes To Maintain Persistent URLs
Answer above using RouteMagic is a good idea, but the example code is wrong (it's included in Phil's post as a bad example).
From the RouteMagic Github demo site global.asax.cs:
// Redirect From Old Route to New route
var targetRoute = routes.Map("target", "yo/{id}/{action}", new { controller = "Home" });
routes.Redirect(r => r.MapRoute("legacy", "foo/{id}/baz/{action}")).To(targetRoute, new { id = "123", action = "index" });
If you specify two routes, you will be setting up an extra mapping that will catch URLs which you don't want.

Ambient values in mvc2.net routing

I have following two routes registered in my global.asax file
routes.MapRoute(
"strict",
"{controller}.mvc/{docid}/{action}/{id}",
new { action = "Index", id = "", docid = "" },
new { docid = #"\d+"}
);
routes.MapRoute(
"default",
"{controller}.mvc/{action}/{id}",
new { action = "Index", id = "" },
new { docConstraint = new DocumentConstraint() }
);
and I have a static "dashboard" link in my tabstrip and some other links that are constructed from values in db here is the code
<ul id="globalnav" class = "t-reset t-tabstrip-items">
<li class="bar" id = "dashboard">
<%=Html.ActionLink("dash.board", "Index", pck.Controller, new{docid =string.Empty,id = pck.PkgID }, new { #class = "here" })%>
</li>
<%
foreach (var md in pck.sysModules)
{
%>
<li class="<%=liClass%>">
<%=Html.ActionLink(md.ModuleName, md.ActionName, pck.Controller, new { docid = md.DocumentID}, new { #class = cls })%>
</li>
<%
}
%>
</ul>
Now my launching address is localhost/oa.mvc/index/11 clearly matching the 2nd route. But when I visit any page that has mapped to first route and then come back to dash.board link it shows me localhost/oa.mvc/7/index/11 where 7 is docid and picked from previous Url.
I understand that my action method is after docid and changing it would not clear the docid.
My question here is, can I remove docid in this scenario without changing the route?
I have the same "not clearing out" value problem...
I've stepped into source code and I don't understand the reason for being of segment commented as : // Add all current values that aren't in the URL at all
# System\Web\Routing\ParsedRoute.cs, public BoundUrl Bind(RouteValueDictionary currentValues, RouteValueDictionary values, RouteValueDictionary defaultValues, RouteValueDictionary constraints) method from line 91 to line 100
While the clearing process is correctly handled in method preceding steps, this code "reinjects" the undesired parameter into acceptedValues dictionary!?
My routing is defined this way:
routes.MapRoute(
"Planning",
"Plans/{plan}/{controller}/{action}/{identifier}",
new { controller = "General", action = "Planning", identifier = UrlParameter.Optional },
new { plan = #"^\d+$" }
);
// default application route
routes.MapRoute(
"Default",
"{controller}/{action}/{identifier}",
new {
controller = "General",
action = "Summary",
identifier = UrlParameter.Optional,
plan = string.Empty // mind this default !!!
}
);
This is very similar to what you're using. But mind my default route where I define defaults. Even though my default route doesn't define plan route value I still set it to string.Empty. So whenever I use Html.ActionLink() or Url.Action() and I want plan to be removed from the URL I call it the usual way:
Url.Action("Action", "Controller", new { plan = string.Empty });
And plan is not included in the URL query string any more. Try it out yourself it may work as well.
Muhammad, I suggest something like this :
(written 5 mn ago, not tested in production)
public static class MyHtmlHelperExtensions {
public static MvcHtmlString FixActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes) {
var linkRvd = new RouteValueDictionary(routeValues);
var contextRvd = htmlHelper.ViewContext.RouteData.Values;
var contextRemovedRvd = new RouteValueDictionary();
// remove clearing route values from current context
foreach (var rv in linkRvd) {
if (string.IsNullOrEmpty((string)rv.Value) && contextRvd.ContainsKey(rv.Key)) {
contextRemovedRvd.Add(rv.Key, contextRvd[rv.Key]);
contextRvd.Remove(rv.Key);
}
}
// call ActionLink with modified context
var htmlString = htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
// restore context
foreach (var rv in contextRemovedRvd) {
contextRvd.Add(rv.Key, rv.Value);
}
return htmlString;
}
}
This is such a frustrating problem and I would venture to say that it is even a bug in ASP.Net MVC. Luckily it's an easy fix using ActionFilters. If you are using MVC3 then I would just put this as a global attribute to clear out ambient values. I made this attribute discriminatory, but you can change it to clear all attributes.
The assumption here is that by the time the Result is executing (your view most likely), you have already explicitly specified all your ActionLinks and Form Actions. Thus this will execute before they (the links) are evaluated, giving you a new foundation to generate them.
public class ClearAmbientRouteValuesAttribute : ActionFilterAttribute
{
private readonly string[] _keys;
public ClearAmbientRouteValuesAttribute(params string [] keys)
{
if (keys == null)
_keys = new string[0];
_keys = keys;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
foreach (var key in _keys) {
// Why are you sticking around!!!
filterContext.RequestContext.RouteData.Values.Remove(key);
}
}
}
// Inside your Global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ClearAmbientRouteValuesAttribute("format"));
}
Hope this helps someone, cause it sure helped me. Thanks for asking this question.
In this particular scenario I have two recommendations:
Use named routes. The first parameter to the MapRoute method is a name. To generate links use Html.RouteLink() (and other similar APIs). This way you'll always choose the exact route that you want and never have to wonder what gets chosen.
If you still want to use Html.ActionLink() then explicitly set docid="" to clear out its value.
Here's how I solved my problem, it may take a little adapting to get it to work, but I felt like I could get what I needed and just use routing more or less normally:
Excerpted from Apress Pro ASP.Net.MVC 3 Framework:
A value must be available for every segment variable defined in the URL pattern.
To find values for each segment variable, the routing system looks first at the
values we have provided (using the properties of anonymous type), then the
variable values for the current request, and finally at the default values defined in
the route. (We return to the second source of these values later in this chapter.)
None of the values we provided for the segment variables may disagree with the
default-only variables defined in the route. These are variables for which default
values have been provided, but which do not occur in the URL pattern. For
example, in this route definition, myVar is a default-only variable:
routes.MapRoute("MyRoute", "{controller}/{action}",
new { myVar = "true" });
For this route to be a match, we must take care to not supply a value for myVar or to make
sure that the value we do supply matches the default value.
The values for all of the segment variables must satisfy the route constraints. See
the “Constraining Routes” section earlier in the chapter for examples of different
kinds of constraints.
Basically I used the rule about a route not matching if it doesn't define a segment, but has a default variable used to give me a little more control over whether a route was chosen for outbound routing or not.
Here's my fixed routes, notice how I specify a value for category that would never be valid and don't specify a segment for category. This means that route will be skipped if I have a category, but will use it if I only have a page:
routes.MapRoute(null, "receptionists/faq/{page}", new { controller = "Receptionist", action = "Faq", page = 1, category = (Object)null }, new { page = #"^\d+$" });
routes.MapRoute(null, "receptionists/faq/{category}/{page}", new { controller = "Receptionist", action = "Faq", page = 1 }, new { category = #"^\D+$", page = #"^\d+$" });
For Category Links
#Html.ActionLink("All", "Faq", new { page = 1 })
#foreach (var category in Model.Categories)
{
#Html.ActionLink(category.DisplayName, "faq", new { category = category.DisplayName.ToLower(), page = 1 })
}
For Page Links
#for (var p = 1; p <= Model.TotalPages; p++)
{
#Html.ActionLink(p.ToString(), "Faq", new { page = p, category = Model.CurrentCategory})
}

Redirecting to same ActionResult from different controllers

I have a User entity, and in various views, I want to create links to a user home page basically. This functionality should be available in different controllers, so I can easily redirect to the user's home page. Each user in my site has a role ; for example reader, writer, editor, manager and admin. Ideally, I want to try to achieve something like this:
In a controller, for example
public ActionResult SomeThingHere() {
return View(User.GetHomePage());
//OR
return RedirectToROute(User.GetHomePage());
}
in a View, I also want to use the same functionality, for example:
<%= Html.ActionLink("Link to home", user.GetHomePage() %>
Is it possible to achieve such a design in MVC? If so , how should I go about it?
I currently use a method like this, but it is only in one controller at the moment. Now I need to use the same code somewhere else and I am trying to figure out how I could refractor this and avoid repeating myself?
....
private ActionResult GetHomePage(User user){
if (user.IsInRole(Role.Admin))
return RedirectToAction("Index", "Home", new { area = "Admin" });
if (user.IsInRole(Role.Editor))
// Managers also go to editor home page
return RedirectToAction("Index", "Home", new {area = "Editor"});
if (user.IsInRole(Role.Reader))
// Writer and reader share the same home page
return RedirectToAction("Index", "Home", new { area = "Reader" });
return RedirectToAction("Index", "Home");
}
...
How about something like this:
private string GetArea(User u)
{
string area = string.empty;
if (User.IsInRole(Admin)) area = "admin";
else if (...)
return area;
}
I would suggest a custom extension to the HtmlHelper class. Top of my head (liable to have syntax errors), something like this
public static class RoleLinksExtension
{
public static string RoleBasedHomePageLink(this HtmlHelper helper, string text)
{
if (user.IsInRole(Role.Admin))
return helper.ActionLink(text, "Index", "Home", new { area = "Admin" });
// other role options here
return string.Empty; // or throw exception
}
}
Then it's just
<%= Html.RoleBasedHomePageLink("Link to home") %>
in your markup.
You don't really want to have a link to somewhere that simply redirects somewhere else, if you can avoid it.
Edit: No idea why I didn't think of this earlier, but if you do need to redirect (perhaps if you need some functionality before going to the home page), you could extend IPrinciple instead
public static class AreaHomePageExtensions
{
public static string GetArea(this IPrinciple user)
{
if (user.IsInRole(Role.Admin))
return "Admin";
// Other options here
}
}
Then you can do
return RedirectToAction("Index", "Home", new { area = User.GetArea() });
whenever you like.
Well I finally came up with a design that seems to work. I have written an controller extension,
with a GetHomePage Method. This extension can also be used in your views. Here is how I did It:
public static class UserHelperExtension {
public static string GetHomePage(this ControllerBase controller, User user) {
return = "http://" + controller.ControllerContext
.HttpContext.Request
.ServerVariables["HTTP_HOST"] + "/"
+ GetHomePage(user);
}
//need this for views
public static string GetHomePage(string httphost, User user) {
return = "http://" + httphost + "/" + GetHomePage(user});
}
private static string GetHomePage(User user) {
if (user.IsInRole(Role.Admin))
return "/Admin/Home/Index";
if (user.IsInRole(Role.Editor))
return "/Editor/Home/Index";
if (user.IsInRole(Role.Reader))
return "/Reader/Home/Index";
return "/Home/Index";
}
}
The action method in the controller looks like this:
using Extensions;
...
public ActionResult SomethingHere() {
return Redirect(this.GetHomePage(user));
}
...
In the view I have this:
...
<%# Import Namespace="Extensions"%>
<%=UserHelperExtension.GetHomePage(Request.ServerVariables["HTTP_HOST"], user)%>
...
The advantage is that I can easily use this "GetHomePage" method in various controllers,
or views thoughout my application, and the logic is in one place. The disadvantage is that
I would have preferred to have it more type safe. For example, in my orignal tests, I had access to RouteValues collection:
public void User_should_redirect_to_role_home(Role role,
string area, string controller, string action) {
...
var result = (RedirectToRouteResult)userController.SomeThingHere();
Assert.That(result.RouteValues["area"],
Is.EqualTo(area).IgnoreCase);
Assert.That(result.RouteValues["controller"],
Is.EqualTo(controller).IgnoreCase);
Assert.That(result.RouteValues["action"],
Is.EqualTo(action).IgnoreCase);
...
}
But now that I am using a string so it is not type safe, and checking the RedirectResult.Url.
...
var result = (RedirectResult) userController.SomethingHere();
Assert.That(result.Url.EndsWith("/" + area + "/" + controller + "/" + action),
Is.True);
...

Resources