Dynamic Mvc route - url

I know there is a lot topics with the same name, but none of those I've found so far, have provided the answer I need.
I'm creating a "dropbox" site for my students to upload their projects on when they have to submit them to me.
The thing is that the students are able to create folders and I would like(if possible) to display the url based on the "folders" they are able to create on the website.
Folders could look like.
Home
Project
Project 1
Project 1 v1
Project 1 v2
And so on.
project 2
Submit
Basic the path could be short or long depends on the folder level.
Like : Home or Project/Project-1-v1/ or Project/Project-1-v1/Upload/Final
Is there a way to create a dynamic url/action that accept any of the above Path's ?

This can be done fairly easy.
My RouteConfig.cs
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute("CatchALL", "{controller}/{action}/{id}/{*catchall}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
My Controller
[Route("Home/{*catchall}")]
public ActionResult Part(string catchall)
{
return View();
}
If this was the url: http://stackoverflow.com/Home/36542665/dynamic-mvc-route catchall would contain = 36542665/dynamic-mvc-route

Related

Asp.Net MVC localizing routes with default language

I need to provide language specific routes for my Asp.Net MVC application. The language should be part of the Url Path (http://myapp/en/Blog) and when it is ommitted the default language have to be used.
http://myapp/en/Blog -> Blog in the English version
http://myapp/Blog -> Blog in the Default (portuguese) Language version
To address this issue I created two Routes bellow:
routes.MapRoute(
name: "Default.lang",
url: "{lang}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { lang = #"^[a-zA-Z]{2}$" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The routes are working as expected but I'm getting weird results when I try to use the Url.RouteUrl method to get alternative language urls.
Example 1 - Path: /
url.Action("Index", "Blog") // returns "/Blog" that is OK
url.Action("Index", "Blog", new { lang = "en" }); // returns "/en/Blog" that is also OK
Example 2 - Path: /en
url.Action("Index", "Home") // returns "/en/Blog" (??????????) Not OK
url.Action("Index", "Home", new { lang = "en" }); // returns "/en/Blog" that is OK
As you can see I get a wrong result when I access the url http://myappurl/en and try to use the Url.Action method without pass any route value (same result with Url.RouteUrl)
Does anyone knows what is wrong with my routes?
[EDIT] I'm not sure if the issue is related to the route because I've tested the routes using "en" as first route's constraint and I got the same result.
After some digging inside System.Web.Mvc and System.Web.Routing source code I found that this behavior is expected. I presume that it is designed to correctly work in applications running inside Virtual Directories.
This can be confirmed in this answer that I found when was researching if someone else had the same problem with virtual path and route resolution.
Workaround
Use named route resolution with Url.RouteUrl method that has and different implementation and works as expected.
Example:
var blogDefaultUrl = url.RouteUrl("Default", new {action = "Index", controller = "Blog"});
var blogLangageSpecifictUrl = url.RouteUrl("Default.lang", new { action = "Index", controller = "Blog", lang = language });
I was avoiding to use named routes because my application design is a little bit more complicated than I demonstrated above. By this reason I have to discover at run time the route that matches the Request.Url and from that point I call the RouteUrl to get the alternative languages url to the content.

index.html is added to our route instead of id

Recently, we've understood that Googlebot has faced 593 server errors in our website. After looking at the links, we understood that instead of id in our route, "index.html" is added.
These is the routes of our site:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "NewsView",
url: "news/{year}/{mounth}/{title}/{id}",
defaults: new { controller = "Home", action = "NewsView" }
);
We have generated the links as below:
#item.Title
This is our website's URL, of course as a sample:
http://www.ourwebsite.com/news/2016/01/this-is-the-title/14747
And this is the URL that Googlebot has faced:
http://www.ourwebsite.com/news/2016/01/this-is-the-title/index.html
In addition, in the "Linked from" tab of Google webmaster, there is the correct URL, which means that the corrupted URL has been linked from the same page with correct URL.
Also, we are using Microsoft URL Rewrite extension, which we have checked and has no rule for this.
Any Help would be highly appreciated

MVC Routing Removes Parameters

My current routing configuration looks as follows:
routes.MapRoute(
namespaces: new string[] { "ChiDesk.WebUI.Controllers" },
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The problem I'm running into is that if I link to the below address:http://localhost:20220/Public/Book?id=c231e3aa-a317-4321-88ef-fe989356babc
The routing appears to remove the id parameter part. So the address in the browser is set to:
http://localhost:20220/Public/Book
This obviously causes a problem if you refresh the page as the id parameter is not included anywhere.
What do I need to change on my routing to sort this out?
Thanks,
Gary
My mistake.
On my document ready function I was setting the history using replaceState. However I was using window.location.pathname property which does not include parameters.
Changing it to window.location has sorted this out.

MVC3 Site Builder Application Design

It would be great if someone could help me on this problem as I am new to web development and ASP.NET MVC. My goal is to design an MVC application which could help users to create their own mini websites. Each user will get their own mini websites and an admin panel to change the pages and template of their sites. I think there are scripts out there to achieve something similar, but we need to create our own for our specific requirements
Towards that goal I created a main mvc 3 application and I created an area as Site under it. We want the user to have their own sub domain urls like www.site1.mainsite.com where site1 is the name of the mini site of the user. For that I added 2 routes one for the main site and another for the area like
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MainSite.UI.Controllers" }
);
In Area Registration
context.MapRoute(
"Sites_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {controller = new SiteConstraint()},
new[] { "MainSite.UI.Areas.Site.Controllers" });
Both of them have the same url type, but area route have a constraint where I added like
var url = httpContext.Request.Headers["HOST"];
var storeName = url.Split('.')[1];
var match = storeName != "mainsite";
return match;
so far its working, But i dont think its a good design. Now apart from this I need to add 2 more areas one is siteadmin and another is blog.
What should be best way to achieve this?
sub domain urls should be directed to area "site"
subdomain url/Admin should be routed to area "siteadmin"
domain/blog should be routed to blog area.
domain other urls should be handled by main controllers
Thanks in advance
I didnt get even one reply :( But I tried playing with the routes and achieved some what near to what I was looking for.
Thanks to Route Debugger, It helped me to see what was going wrong with the routes
When I tried adding another area "Admin", and registered it with the route below
context.MapRoute(
"SiteAdmin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional },
new { controller = new SiteConstraint() },
new[] { "MainSite.UI.Areas.SiteAdmin.Controllers" }
);
Things started going wrong. Route Debugger helped to me to figure out, what was happening.
For me the order of the Routes really mattered, so I had to make sure that my areas were registered in the correct order.
AreaRegistration.RegisterAllAreas()
was not registering my routes in the correct order, Googling gave me this helper method.
public static class RouteHelper
{
public static void RegisterArea<T>(RouteCollection routes, object state) where T : AreaRegistration
{
var registration = (AreaRegistration)Activator.CreateInstance(typeof(T));
var context = new AreaRegistrationContext(registration.AreaName, routes, state);
var tNamespace = registration.GetType().Namespace;
if (tNamespace != null)
{
context.Namespaces.Add(tNamespace + ".*");
}
registration.RegisterArea(context);
}
}
That method helped me to register the areas in the required order in the Global asax as
RouteHelper.RegisterArea<SiteAdminAreaRegistration>(RouteTable.Routes, null);
RouteHelper.RegisterArea<SiteAreaRegistration>(RouteTable.Routes, null);
I am writing it down, what I got so far as an answer so that someone else may be find it useful.

Having issue with multiple controllers of the same name in my project

I am running into the following error with my ASP.NET MVC 3 project:
Multiple types were found that match
the controller named 'Home'. This can
happen if the route that services this
request ('Home/{action}/{id}') does
not specify namespaces to search for a
controller that matches the request.
If this is the case, register this
route by calling an overload of the
'MapRoute' method that takes a
'namespaces' parameter.
The request for 'Home' has found the
following matching controllers:
MyCompany.MyProject.WebMvc.Controllers.HomeController
MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController
I have a HomeController in my default controller folder, with a class name of MyCompany.MyProject.WebMvc.Controllers.HomeController.
My RegisterRoutes method, in my global.asax, looks like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I then have an area called Company, with a HomeController in the default controller folder for the area, with a class name of MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController.
The RegisterArea method in the CompanyAreaRegistration file looks like:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Company_default",
"Company/{controller}/{action}/{id}",
new { area = "Company", action = "Index", id = UrlParameter.Optional }
);
}
This is all leading the error I highlighted at the beginning of this post. I am struggling trying to piece together a solution from various other posts, with NO LUCK.
Is it possible to have a HomeController in the default controllers folder and then one in EACH area? If so, do I need to make (assuming I do) changes to my configuration file to make this work?
Any help would be much appreciated!
The error message contains the recommended solution: "If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter."
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);
This will make http://server/ go to your HomeController's Index action which is, I think, what you want. http://server/company/home will go to the Company area's HomeController's Index action, as defined in the area registration.
This is the asp.net mvc4 approach:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "RegisterNow", id = UrlParameter.Optional },
namespaces: new[] { "YourCompany.Controllers" }
);
I had renamed the namespaces, so, i only delete de folders bin and obj and rebuild, work again.
If you're using RazorGenerator, just informing the namespaces parameter could be not enough.
I got to solve adding the statement marked below at Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ControllerBuilder.Current.DefaultNamespaces.Add("MyProject.Controllers"); // This one
}
Another plausible cause of this issue could be found below:
Multiple types were found that match the controller named 'Home'
use this
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ProjectName.Controllers" }
);
Use only the name of the project:
Public Class RouteConfig
Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
, namespaces:={"MvcAreas"})
End Sub
I had the same issue and found that the older version had created compiled files in the "bin" folder.
Once I deleted these the error disappeared.
As Chris Moschini mention the namespaces parameter may not be enough if you have two areas with same controller name with different namespaces and the default none area route will return 500 server error.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);
It "best" to override the default route handler and add this line:
RequestContext.RouteData.DataTokens["UseNamespaceFallback"] = false;
I had this issue after I added a reference to another project that had the same routes and the problem continued after I removed the reference.
Resolved by deleting the .dll file of that added reference from the bin folder and rebuilding.
Like many others, I had this problem after creating a new MVC template project from VS2017 menu, on building the project I would get the op's error message. I then used the answer https://stackoverflow.com/a/15651619/2417292 posted earlier in this thread by cooloverride
for mvc4 projects.
This still didn't fix my issue so I renamed my Home view folder and HomeController file to be the view folder Company/ and controller file CompanyController. This then worked for me, not a fix per say but a workaround if your not stuck on having the route Home/Index my other issue was I couldn't find the reference causing the error and due to my dev platform being Azure WebApplication vs a full VM with a complete file system and IIS settings to mess with.
For MVC5 below code works for issue same controller name for different areas. You have to specify which area controller have to hit first.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ApplicationName.Areas.AreaName.Controllers" }
).DataTokens.Add("area", "AreaName");
This issue occurred when I accidentally added
[Route("api/[controllers]s")]
instead of
[RoutePrefix("api/[controllers]s")]
to the top of my ApiController.

Resources