Hiding action in url (mvc 4 web application) - asp.net-mvc-3

I have a module called News as Area. In NewsAreaRegistration I have
context.MapRoute(
"NewsShow",
"News/{controller}/{friendlyUrlName}/{idNews}",
new { controller = "Show", action = "Index", friendlyUrlName = "", idNews = "" }
);
In my view (in main View folder) I use RouteUrl method to enforce my custom route
#Url.RouteUrl("NewsShow", new { controller = "Show", action = "Index", friendlyUrlName = FriendlyURL.URLFriendly(true, Model.News.Data.ElementAt(0).Title), idNews = Model.News.Data.ElementAt(0).IdNews})"
What I would like to do is have a route like this www.something.com/News/Show/bla-bla-bla/9
without action name Index that I have in Show controller. I tried literaly all permutations of this example and nothing worked. Is this even possible?

Ok, so I tried this out....
Routing table: (before default)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Hidden",
url: "News/{controller}/{friendlyUrlName}/{idNews}",
defaults: new {controller = "Home", action = "Index", friendlyUrlName = "", idNews = ""});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
In the View:
#Url.RouteUrl("Hidden", new { friendlyUrlName = "Dude-Check-It-Out", idNews = 12 })
in my controller:
public ActionResult Index(string friendlyUrlName, int idNews)
{
ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";
ViewBag.UrlName = friendlyUrlName;
ViewBag.NewsId = idNews;
return View();
}
and I got this..
/News/Home/Dude-Check-It-Out/12
URL I go to:
http://localhost:49840/News/Home/Dude-Check-It-Out/12
I also changed my default route to something else to ensure that this wasn't using the default route. Let me know if this helped :)

Did you put this route before default one? Route position is important, from top to bottom.

Ok...I managed to work somehow.
In my NewsAreaRegistration I had to move NewsShow route before default. Not sure why, becuase RouteUrl should map excatly to NewsShow.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"NewsShow",
"News/{controller}/{friendlyUrlName}/{idNews}",
new { controller = "Show", action = "Index", friendlyUrlName = "", idNews = "" }
);
context.MapRoute(
"News_default",
"News/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
This is my RouteUrl now (notice I had to write controller.Not sure exactly why either:
#Url.RouteUrl(
"NewsShow", new { controller = "Show", friendlyUrlName = FriendlyURL.URLFriendly(true, Model.News.Data.ElementAt(0).Title), idNews = Model.News.Data.ElementAt(0).IdNews }
);

Related

mvc3 URL routing without action

I have a controller named article and my articles in the url take the shape of {controller}/{action}/{id}/{title}/{mixed} how can i get that to {controller}/{id}/{title}/{mixed}
my route value is
routes.MapRoute(
"articles",
"{controller}/{action}/{id}/{stitle}/{mixed}",
new { controller = "article",action="detail",mixed= UrlParameter.Optional} // Parameter defaults
);
I have tried this
routes.MapRoute(
"articles", // Route name
"{controller}/{id}/{title}/{mixed}",
new { controller = "article",action="detail",mixed= UrlParameter.Optional}
);
but get a 404 error
as my links are in the form
#Html.ActionLink("My article", "detail", "article", new { id = item.ArticleID, title = item.title, mixed = item.mixed })
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ArticleWithoutAction", // Article Without Action name
"{controller}/{id}/{name}",
new { controller = "Article",
action = "detail",
id = UrlParameter.Optional,
title = UrlParameter.Optional,
mixed = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"ArticleWithAction", // Article With Action name
"{controller}/{action}/{id}/{name}",
new { controller = "Article",
action = "detail",
id = UrlParameter.Optional,
title = UrlParameter.Optional,
mixed = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}",
new { controller = "Article",
action = "detail"
} // Parameter defaults
);
}

Can't find Controller in MVC 3 project - NotFound error

I have this global.asax file with this code:
routes.MapRoute("Invitations",
"api/invitations",
new { controller = "Invitations", action = "Invitation"});
And I have a Controller:
public class InvitationsController : Controller
{
[HttpPut]
public JsonResult Invitation(InvitationResponse invitationResponse)
{
//code
}
}
And I'm accessing the controllers by HttpWebRequest with this URL:
"http://localhost:6055/API/Invitations"
When I run this I get the error "NotFound".
EDIT:
The whole global route:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Users",
"api/users/{id}",
new { controller = "Users", action = "UserAction", id = UrlParameter.Optional });
routes.MapRoute("CheckIn",
"api/checkins",
new { controller = "CheckIn", action = "CheckIn" });
routes.MapRoute("Appointments",
"api/appointments/{id}",
new { controller = "Appointments", action = "Appointment", id = UrlParameter.Optional });
routes.MapRoute("UserAppointments",
"api/users/{userId}/appointments/{startDate}",
new { controller = "Appointments", action = "UserAppointments", startDate = UrlParameter.Optional });
routes.MapRoute("UserInvitations",
"api/users/{userId}/invitations",
new { controller = "Invitations", action = "UserInvitations" });
routes.MapRoute("UserOverview",
"api/users/{id}/overview",
new { controller = "Users", action = "Overview" });
routes.MapRoute("Invitations",
"api/invitations",
new { controller = "Invitations", action = "Invitation"});
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
"http://localhost:6055/API/Invitations" doesn't look correct, shouldn't it be
"http://localhost:6055/YourApp/API/Invitations"

mvc3 areas have hostname

I am looking to create a MVC3 website. We need at least two areas but we need different url's for each of the areas. Like this:
domain.com/ goes to /
admin.domain.com/ goes to /areas/admin
anotherSite.com/ goes to /areas/portal
After doing some research I have found Lucero's link that you can use HostNameContraint as follows:
public class HostNameContraint : IRouteConstraint
{
protected string _hostname;
public HostNameContraint(string hostname)
{
_hostname = hostname;
}
bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext.Request.Url.Host == _hostname)
return true;
return false;
}
}
and then register the constraints like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("domain.com") },
new[] { "MVCProject.Controllers" }
);
routes.MapRoute(
"Admin_Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("admin.domain.com") },
new[] { "MVCProject.Controllers.Areas.Admin.Controllers" }
);
routes.MapRoute(
"Portal_Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { area = "Portal", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("anotherSite.com") },
new[] { "MVCProject.Controllers.Areas.Portal.Controllers" }
);
I have IIS setup so that they point to the root folder of the application for each of the sites. Pointing to the root "Domain.com" works fine but going to either "Admin.domain.com" or "Domain.com/admin/" comes up with a 404 "Resource cannot be found."
Update
I have tried it both with the Area name at the beginning of the url and without.
"Portal/{controller}/{action}/{id}"
The issue is that when the "Portal" area is in the route, the signature does not match the name as "anotherSite.com" and therefore it comes back and says 403.14 - Forbidden. Cannot list contents of this directory. It is also important to note that the constructor for HostNameConstraint is never called when the "Portal" area is url parameter.
In order to indicate distinguish the URL as going to an area, the area name needs to be part of the URL. Otherwise, the area will not be parseable from the URL and you will fall back to the default routing. Also, it is a good idea to put your default route last - to ensure all other route mappings are tested
Note the addition of "Admin/" and "Portal/" in the corresponding MapRoute call:
routes.MapRoute(
"Admin_Default2", // Route name
"Admin/{controller}/{action}/{id}", // URL with parameters
new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("admin.domain.com") },
new[] { "MVCProject.Controllers.Areas.Admin.Controllers" }
);
routes.MapRoute(
"Portal_Default2", // Route name
"Portal/{controller}/{action}/{id}", // URL with parameters
new { area = "Portal", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("anotherSite.com") },
new[] { "MVCProject.Controllers.Areas.Portal.Controllers" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { hostname = new HostNameContraint("domain.com") },
new[] { "MVCProject.Controllers" }
);

ActionLink with /Controller/Action/Id/Id2

How can I have an action link with two Ids. (I am using areas). The Id2 gets rendered as a querystring.
Controller
public ActionResult View(int id, int id2)
Route
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"Admin_default2",
"Admin/{controller}/{action}/{id}/{id2}",
new { action = "Index"}
);
ActionLink
#Html.ActionLink("Click", "News/View", new { area = "Admin", id = 1, id2 = 2 }, null)
Rendered Link
/Admin/News/View/1?id2=2
Expected Link
/Admin/News/View/1/2
Try adding the more specific route (Admin_default2) first.
So, your mapping code would look like:
context.MapRoute(
"Admin_default2",
"Admin/{controller}/{action}/{id}/{id2}",
new { action = "Index"}
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);

ASP.NET routes problem

If i go to mysite/Catalog it breaks. How can solve it?
routes.MapRoute(
"Localization", // Route name
"{lang}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = 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
);
routes.MapRoute(
"Root",
"",
new { controller = "Home", action = "Index", id = "" }
);
It will match your first route thinking "Catalog" is "lang". You need to create constraint for your localizations.
Following route should match requests prefixed with any language code (like en, cs, de or en-US, en-GB...) correctly
routes.MapRoute("Localization", "{lang}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { lang = "[a-z]{2}(-[a-z]{2})" }
);

Resources