I'm working with ASP.NET MVC3, I created my routes and compose my urls but I have something weird in my url after navigated in browser.
Url actually rendered: /controller/action/page.html
Url navigated: /controller/action/page.html#.V7cdQJh97cw
I think that maybe is SessionID but I can't know how to remove it.
Appreciate any helps!
Go to the RegisterRoute method of RouteConfig.cs file in the App_Start folder of your project where Default Routing rule is written there.
Route Rule:- ControllerName/ActionName/id
where id is optional. So you want to remove Id parameter ,then make Id=" ".
for example:-
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 = "" } // Parameter defaults
);
}
Related
I need to rebuild a website (in old they use classic ASP but they want to make it now MVC 4) and they dont want to change the urls. for example if the search screen's url is blabla.com/search.asp they want to keep it like this. But mvc doesn't allow to make urls like "search.asp". I want to keep url like this but render search View. Am I need to do this all one by one or there is a dynamic way for it?
for example
requested url = "blabla.com/string variable"
if variable.Substring(variable.Length - 4) == ".asp";
return View("variable.Substring(0, (variable.Length - 4))")
Note: Syntax is all wrong, I know. I just tried to explain the condition..
Note2: They want this because of "SEO" things. they don't want to lose their ratings. any method that doesn't change anything for google, they will accept that method I guess.
You need two things.
Define a route for *.asp
Add an handler for *.asp
RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultAsp",
url: "{controller}/{action}.asp/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Handler (WebConfig)
(This one needs to be inserted inside /system.webServer/handlers
<add name="AspFileHandler" path="*.asp" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Doing this you are also making all URL's built with MVC available with .asp, that means that if you have an anchor that calls another View, that view will have the normal mvc URL with .asp suffix.
Note
This is generic, you only need to add this line once.
Home/Index displayed are just the default Controller and Action.
Note 2
Forgot to explain the handler.
You need it because IIS thinks you are asking for an ASP file an it'll try to reach that page and return an error since it doesn't exist.
With this handler you are allowing your application to handle those pages itself.
MVC does allows you to write a Route containing an extension, and pointing it to a specific Controller:
In RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("Test", "test.asp", new {controller = "Test", action = "test" });
}
Then, in your TestController.cs:
public class TestController : Controller
{
public ActionResult Test()
{
var obj = new Foo();
//Do some processing
return View(obj);
}
}
In this way, you can access http://www.foo.com/test.asp without issues, and maintaining the .asp your client requires.
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.
I've looked for a solution to this but even the simplest examples aren't working properly. Passing a single parameter {id} works successfully but that's the only parameter that is working. Changing the single parameter to anything else fails. In the example below multiple parameters also fail. It seems as the only workable parameter is "id".
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Servers",
url: "{controller}/{action}/{id}/{a}",
defaults: new
{
controller = "Test"
}
);
}
public class TestController : Controller
{
[HttpGet]
public ActionResult Monster(string id, string a)
{
return Json(new { success = id }, JsonRequestBehavior.AllowGet);
}
}
The url localhost/Test/Monster/hi Successfully reads the parameter as "hi". Specifying localhost/Test/Monster/hi/hello fails and gives a 404.
Try this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Servers",
url: "{controller}/{action}/{id}/{a}",
defaults: new
{
controller = "Test",
id = UrlParameter.Optional,
a = UrlParameter.Optional
}
);
}
Also, is this your only route?
The order that the routes are set-up in is important, it's very easy to overwrite a route with a later route. I have done that mistake countless times.
In case action is not optional, you should specific the default value for it. Please try :
routes.MapRoute(
name: "Servers",
url: "{controller}/{action}/{id}/{a}",
defaults: new
{
controller = "Test",
action = "Monster"
}
);
In your method you have specified the parameter string a so when you pass the URl localhost/Test/Monster/hi/hello MVC will look for the parameter a in the url as it matches the form post parameters with the parameters in the function
So this link might help you as it helped me
http://www.codeproject.com/Articles/299531/Custom-routes-for-MVC-Application
This is a very late response but the issue with this was that there was an area being registered further downstream that was causing the routing issues. The area being registered had an optional url parameter that was taking the routes over. Utilizing this registered area fixed the issue.
sorry to say but as you saying
localhost/Test/Monster/Hi
working mean only one parameter routing is configured... did you try by restarting the IISExpress as routing get loaded on very first call and one time only..
after making the changes in routing you have to stop the IIS Express from the Icon Tray and re-run you project then with one parameter it should throw error.. as you have not set these option it will work only when u specify both the parameters.
How do I handle url like this:
{subdomain}.{domainname}/{areas}/{controller}/{action}
For example: user1.contoso.com/Manage/User/View
I want it to be route:
{area} = Manage
{controller} = User
{action} = View
{username} = user1 // View action parameter
Any help would be greatly appreciated :-)
Generally routes are defined in the file Global.asax in the method RegisterRoutes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Export", // Route name
"Export/{action}/{table}", // URL with parameters
new { controller = "Export", action = "AsExcel", table = "" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
With a definition like above you can use a separate route for ExportController such that the default action is AsExcel
in the case of route as the one you have described, I am not sure if Areas is part of the MVC pattern.
Still for what it is worth, you may have some benefit from this thread
ASP.Net MVC with complex routes - how to keep it "sane"?
Some background:
I create a new ASP.NET MVC 3 WebApplication.
Then I add a Webforms page: ~/ASPWebforms/Test.aspx
Then I edit the routing in the Global.asax file like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("Test", "Test/", "~/ASPWebforms/Test.aspx");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now I type in my browser http://localhost:54847/Test and everything works as expected.
The problem is that all other links look like that: http://localhost:54847/Test?action=Index&controller=Home
I also tried to change the order of the routes:
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 }
);
routes.MapPageRoute("Test", "Test/", "~/ASPWebforms/Test.aspx");
}
but then http://localhost:54847/Test won't work anymore.
I'm expecting the link http://localhost:54874/Test to go to ~/ASPWebforms/Test.aspx
And the other links work as usual mvc style {controller}/{action}/{id}
Thx for your help!
I can help with the second doubt.
The reason why it wont work is because the routes order is important.
http://msdn.microsoft.com/en-us/library/cc668201.aspx
whenever it finds a match, no more routes will be tested to that request.
I found a solution for the first problem on this page:
http://forums.asp.net/p/1589809/4028028.aspx
An interesting sentence from this page:
Please read the topic "Understanding the Outbound URL-Matching
Algorithm" in Steve book.