How to use URL parameter as a key in MVC application? - asp.net-mvc

In my MVC application , RouteConfig contains following code (by default):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{key}",
defaults: new { controller = "Home", action = "Index", key= UrlParameter.Optional }
);
}
When a user hits my website (abc.com) or type abc/Home/Index , it invokes Home/Index. Problem is that I want to use key. I mean If a user enters abc/someKey or abc/Home/Index/someKey it should go to Home/Index where i can access that key. It works good in abc/Home/Index/someKey case but fails in abc/someKey & gives exception. Is there any other way to get that functionality ?

Related

Problems deploying mvc app to sub directory of site

When i place all my files in the root of my site, it overrides the existing site and automatically goes to the calendar application instead of the index.php that i have.
I have an existing site that i cannot change, so i was wondering how i can deploy this in a subdirectory, ex mysite.com\mvc_app\Home\Index
Here is my routing for the route config, any help would be appreciated! (i tried ignoring the blank route but it seems to open the app still, even tho hostbuddy is set to route mysite.com to the index.php as the default page)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

setup asp.net mvc route for base url

When I have this route setup I can trigger any controllerName/actionName url because I do not need a start url/page.
I do not run a web api because I want to use razor for my views.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "*", action = "*", id = UrlParameter.Optional }
);
}
but when I start my project and run my site I see the base url in the browser: http://localhost:62127/
giving me a 404 error.
How can I configure my project to return a 403 error which is IIS typically giving me? When directory browsing is disabled?

MVC routing Index/id actions goes to server root

If I have an ActionLink which points to Server/Site/Prices/Index/24, (with Prices being the controller and Index being the Action) what it actually does is navigate to Server/24, which obviously provides a 404. The same thing if I go to Server/Site/Options/Index/15,(with Options being the controller and Index being the Action) what it actually does is navigate to Server/15.
I find it even more strange that it is going to the server root, not the site root.
This works fine running IIS Express on my dev machine. However on the server it is acting strange when navigating to actions called Index. I'm using VS2013 Publish to deploy.
If I change the Index Action name to something different, then that will work
I initially thought this was just a single controller issue, but then came across another controller Index action doing the same thing.
My RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
My action links look like this
#Html.ActionLink("Options and Prices", "Index", "Prices", new { id = option.Id }, new { #class = "btn btn-primary btn-sm" })
To add to this, if I deploy to a different server and it works correctly. Also works fine locally with IIS Express. Suggests it's some IIS setting somewhere.

URL Routing: a link redirects when not followed by /

I have come across the most bizarre of problems: I have a login page in an MVC application, which when linked by /login will automatically redirect to the home page. However, if I use /Login or /login/, it works!
I have no idea whether it's something to do with a configuration I've messed up, or a configuration in the routing I've played around with, but it happens exclusively with the login page.
I am using forms authentication, and have tried changing the page that you're redirected to from the login page, but that doesn't seem to help at all.
Any ideas?
Update: this only happens on my local machine. I host with Windows Azure, and it works fine when deployed.
Edit: current routing configuration:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }
);
routes.LowercaseUrls = true;
}

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