I got two controllers in a VS 2015 web app the I define a regular menu using asp tag helpers to call each view, one of the options in that menu uses another control however is always calling the same controller, I am not sure if something changes now with MVC 6.
I was using the following routes:
config.MapRoute(
name: "Event",
template: "Event/{action}",
defaults: new { controller = "Event", action = "Index" }
);
config.MapRoute(
name: "App",
template: "App/{action}/{id?}",
defaults: new {controller="App",action="Index"}
);
From what I've found, by default, one has to use attributes to setup routing in MVC 6. There is a shim (see http://www.strathweb.com/2015/01/migrating-asp-net-web-api-mvc-6-exploring-web-api-compatibility-shim/) to allow the compatibility with the method you are attempting.
This page (http://www.ryadel.com/en/custom-routing-method-names-in-asp-net-5-mvc-6/) is a little misleading because it makes it sound like there is a choice between MapRoute and/or using attributes. Regardless, it has some good examples.
Summary: Delete all calls to MapRoute and use attributes in your controllers.
Related
Working with ASP.NET MVC3, site is in beta and customer decided to rename one of the controllers.
http://domain.com/foo[/*] -> http://domain.com/bar[/*]
What is the most straightforward way to handle redirecting so I don't break any foo bookmarks?
Keep the old controller around so the old URLs still work.
Or add a rewrite rule. Something like:
domain.com/foo(/[_0-9a-z-]+)
to:
domain.com/bar{R:1}
URL Rewrite in IIS
http://technet.microsoft.com/en-us/library/ee215194(WS.10).aspx
http://www.iis.net/download/URLRewrite
If you are using MVC.NET you probably already have URL Rewrite installed.
Another option would be to register a specific route for the old controller name in the Global.asax.cs.
routes.MapRoute(
"RenamedController", // Route name
"[OldControllerName]/{action}/{id}", // URL with parameters
new { controller = "[NewControllerName]", action = "Index", id = "" } // Parameter defaults
);
Add that before the standard default route, and your new controller should respond to both old and new names.
A 302 redirect would be fine, if you can figure out how to do that in IIS. This screenshot suggests it's not that arduous. Alternately, if you're using Castle Windsor you may want to register an interceptor that uses HttpResponse.Redirect()
REST standard suggests the best way to handle this issue is by returning a 301(Moved permanently request). Stack Overflow Post REST Standard
In .Net I recommend using Controller.RedirectToActionPermanent in your controller. See: ASP.NET, .NET Core
Code Example(should work for both ASP and Core):
public class MyController : ControllerBase
{
public IActionResult MyEndpoint(string routeValues1, string routeValues2)
{
return RedirectToActionPermanent("action", "controller", new { value1 = routeValues1, value2 = routeValues2 });
}
}
using MapRoute doesn't make sense in this case. MapRoute is really meant to provide a custom routing solution throughout the system. Its not really meant to deal with individual Redirects. As far as I'm aware it doesn't actually inform the user they are being redirected. See: Creating Custom Routes (C#)
MVC has great tools for building urls inside an MVC app by using routing. Routing by controller and action lets us avoid hard coding urls in markup.
But we have a bunch of ancillary services that need to create urls for marketing emails.
For instance, our email marketing campaigns may need to build a url for an offer. The MVC app knows how to build the url to the offer detail, but is there a clever way of doing this for the service app? Can we/should we move routing into a separate dll and reference it from one place?
Success stories/horror stories are appreciated.
it sounds like you should be using a catchall url to lookup actions you can manage in a DB such as:
Route like this
routes.MapRoute(
"MailCampaigns",
"/mailcampaigns/{*url}",
new {controller = "MailCampaigns", action = "Incoming" }
);
public ActionResult Incoming(string url)
{
//parse the url and perform actions accordingly
var actionInfo = repository.Query<ActionInfo>().Where(x => x.Url == url).SingleOrDefault();
return Redirect(actionInfo.TargetUrl);
}
I'm using ASP.NET MVC 3 (Razor) and have created a Controller named "Controllers" - specifically, the Controller class name is "ControllersController".
Here's a snippet of my "Controllers" Controller:
public class ControllersController : Controller
{
public ActionResult Index()
{
return View();
}
}
In addition to creating the ControllersController class, I created a Razor View (Index.cshtml) that correlates with the ControllersController Index() action. It may be worth noting that I created the Index.cshtml View by right-clicking the Index() method within the Controller and choosing "Add View".
The problem that I am experiencing is, when a browser tries to go to http://localhost/controllers, the following error is thrown:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource
you are looking for (or one of its
dependencies) could have been removed,
had its name changed, or is
temporarily unavailable. Please
review the following URL and make sure
that it is spelled correctly.
Requested URL: /controllers/
There are two points that I'd like to point out:
The error can be avoided if the
browser explicitly goes to
http://localhost/controllers/index
Controllers that are not named
ControllersController don't force
the browser to specify the /index
action in its URL.
With all the naming conventions in MVC, I'm not surprised that a Controller named Controllers causes some strange behavior. My question is; what do I need to do so that I don't have to specify /index in the browser's URL?
This is because you have a folder called "Controllers" on disk in your project. One option would be to rename that folder to something else. This problem won't exist when you publish your site using the Visual Studio publish option because the Controllers folder won't get pushed. A second more cumbersome solution would be to set routes.RouteExistingFiles = true; in the RegisterRoutes function in your global.asax.cs. You then may want to call route.IgnoreRoutes for items in your content folder, etc.
Stay away from using any current names in your code - the world will be a better place, children wont cry, etc.
"With all the naming conventions in MVC, I'm not surprised that a Controller named Controllers causes some strange behavior. "
If it feels weird - don't do it : )
Apparently, the problem has nothing to do with the name of the Controller (i.e. ControllersController), but rather with the name of the URL route.
In my Global.asax.cs, I added a custom route as follows:
public static void RegisterRoutes(RouteCollection routes)
{
//Route /controllers/ to /Home/Index
routes.MapRoute(
"Controllers",
"controllers/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Notice the the custom route (named "Controllers") routes to the HomeController (not ControllersController).
I would expect that when the browser points to http://localhost/controllers, MVC would return the /Home/Index page. Instead, a 404 error is thrown. However, the route succeeds if the browser points to http://localhost/controllers/index. - This is the same symptoms as I mentioned at the beginning of this post.
Based on this test, I think it's safe to assume that the problem is not with the naming convention of the Controller, but rather with the naming convention of the MVC routing.
To move on with building my application, I'm going to change the name of my ControllersController to ControllerSystemsController. In the meantime, I'm interested to know specifically why the MVC router doesn't work as expected for routes that use "controllers" as the name of the controller. Can anyone shed light on this?
My environment consists of Visual Studio 2010 and Windows 7 a few months ago I developed an MVC2 application with no problems however after trying to create a new project recently I received the error below.
I did find the link http://support.microsoft.com/kb/894670 but this is not relevant because I am not using IIS for testing, just F5 to get this working :)
Any ideas or help would be appreciated.
Server Error in '/' Application.
--------------------------------------------------------------------------------
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4927
The Empty MVC 2 template application does not define any controllers or views. When you create a new Empty MVC 2 application and immediately run it, you will see the error message you posted.
If you check the Global.asax file, you'll see that the project template automatically registers a default route specifying a default controller named "Home" and a default action named "Index".
To get this to run, right-click on the Controllers folder, then choose Add->Controller... Name the controller "HomeController". You can leave the check box to "Add action methods for Create, Update, Delete..." unchecked.
In the HomeController.cs file, right click in the Index() method and choose Add View...
Leave the View name as "Index", uncheck "Select master page", and then click Add.
In the Index view, you can enter some HTML and run the project; you should now see the page rendered by Index.aspx.
One thing I am not sure of is why your error message lists the .NET Framework version as 2.0. If you still have problems, check the target framework on your project properties.
Make sure that the routes are set properly and that you have default values for a controller and action. For example if you have the following route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
Make sure that you have a HomeController with an Index action.
I have an existing ASP.Net Application, into which I am attempting to introduce MVC2.
Hopefully I can remember the steps, but what I did was the following:
Created a dummy MVC2 project.
Compared and merged .csproj, resulting in the Add Item commands showing MVC2 items.
Compared and merged the web.config
Compared and merged the global.asax.cs
Added Models, Views and Controllers directories
Added HostController with Index action and Index.aspx (no logic)
Amended route to make /Host/Index the default
So now, when I access the application via the root address http://localhost/MyApp it all works.
But, when I access http://localhost/MyApp/Host/Index I get a 404 error. I get the same result for any of the Controller/Actions I created. The only way I can get them to appear is to use the defaults in the routing configuration. I installed Phill Haack's route debugger and it's doing nothing. Obviously there's some problem with my routing, but I can't figure it out.
Any ideas what I've missed?
Bah... turns out that this is to do with IIS 5.1 and MVC routing.
I resolved it by using the following Routes in my application (note the .aspx extensions).
routes.MapRoute("Root", "", new { controller = "Host", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}.aspx", new { controller = "Host", action = "Index" });
Means I can't have clean routes, but at least it works.