I have a question about MVC3 in the Pluralsight examples. I'm new to MVC and I have what will appear to be a simple question. I downloaded the sample code and added the Routemap to global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace OdeToFood
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "Search" }
);
/* routes.MapRoute(
"Cuisine",
"{controller}/{name}",
new { controller = "cuisine", action = "Search" }
); */
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
And added the Controller:
namespace OdeToFood.Controllers
{
public class CuisineController : Controller
{
//
// GET: /Cuisine/
public ActionResult Search()
{
return Content("You have reached the Cuisine controller");
}
}
}
As shown in the tutorial "Controller Action Parameter!" and run the application with the word cuisine (all spelled correctly - even changing to all capitalization as a test) and I still get the HTTP 404 "not found error".
I'm running on Windows 7 with VS 2012 and .net 4.5 installed (this is a new box and may not have ever had previous versions. MVC 3 and MVC 4 are in the new project selection so those must be isntalled correclty.
Any ideas on what I'm doing wrong? Did I miss a step? I see that IIS6 or IIS7 might/must be on the machine? I have come to believe that IIS doesn't run on windows 7. Is that true? Do I require iis? The sample code works fine until this change...
I'm a little over my head here as I learn this new stuff. Thank you for your patience and help!
Try using:
routes.MapRoute(
"Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "Search", name = "" }
);
Try using the a MVC Route Debugger so that you can visually see which routes are being matched. The one I use is Phil Haack's, but there are others available:
Install-Package RouteDebugger
Separately, don't you need a name parameter on your search action to match this route?
Related
I have problem with one area in my project called 'Reports'. I always get 404 error when I try to access some controller from this Area. This problem only occurs when I run my application on local IIS (Windows 8.1). On other machine (windows 7 and local IIS) everything is ok. Even on this windows 8.1 machine, but IIS Express everything is working well.
I was trying to clear temp files, but no resuls.
Areas are registed such like this:
public class ReportsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Reports";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Reports_default",
"Reports/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
And in Global.asax, Application_start() method:
AreaRegistration.RegisterAllAreas();
I dont know where could be the problem. Do you have any ideas?
Check event viewer. I had this problem and the 'Reports' URL was a virtual directory having to do with SQL Server Reporting Services.
Try this:
public class ReportsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Reports";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Reports_main",
"Reports/{controller}/{action}/{id}",
new { area = "Reports", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"Reports_default",
"Reports/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
The Reports_default routing rule sets Index to be the default action for a given controller.
You need to add another Reports_main rule that will set a default controller when you access the root of the area e.g. /Reports. In this rule I assume that the default controller is Home but you can change that to fit your project.
The default AreaRegistration scaffold by Visual Studio does not include a default for controller, meaning that providing a controller in the URL is required.
/Reports/Home // This works (if you have a home controller)
/Reports // This doesn't work
To make the controller optional, you need to provide a default.
public class ReportsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Reports";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Reports_default",
"Reports/{controller}/{action}/{id}",
// Note that controller is defaulted to Home
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Note also that the order in which routes are registered is the same that they will be executed for the entire application. Typically, this means that you must call AreaRegistration.RegisterAllAreas() before you call RouteConfig.RegisterRoutes(RouteTable.Routes).
The answer provided by Tasos will also work, but is incorrectly configured:
Specifying a default area within an AreaRegistration is redundant and unnecessary.
Reports_default in his example is an unreachable execution path, which makes it also redundant and unnecessary.
I am developping a WEB API using asp.net and my goal is to be able to call this type of url's:
/html/countries/...
/json/countries/...
Countries is a controller, and depending on the parameter before it returns different result.
What i did and it doesn't seems to work:
routes.MapRoute(
name: "Default",
url: "api/{action}/{controller}",
defaults: new
{
}
);
CountriesController:
[ActionName("html")]
public string get()
{
//...
}
[ActionName("json")]
public void getType()
{
//...
}
Any sugestions?
EDIT:
I have like 7 controllers.
And there are some possible urls:
/html/{controller}/x/y
/json/{controller}/x/y/order/h
/html/{controller}/x/z/order/y/j
/json/{controller}/x/z/order/y/j
Allow me by start saying that if "html" or json action means "format" those should not be part of your controller they are media types and needs to be configured differently
Web Api v1 defines resources globally in the global.asax on application_start event. Assuming you are using Visual Studio 2013 and based Microsoft default template your method may look like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApi routing configuration occurs here WebApiConfig.Register while your MVC configuration occurs here RouteConfig.RegisterRoutes
Your WebApi routing configuration should look like this
public static class WebApiConfig{
public static void Register(HttpConfiguration config){
config.Routes.MapHttpRoute(
name: "htmltApi",
routeTemplate: "html/{action}/{controller}",
);
config.Routes.MapHttpRoute(
name: "jsonApi",
routeTemplate: "json/{action}/{controller}",
);
...
Another important detail is that WebApi v2 introduced something called Route Attributes those can be used along with your Controller class and can facilitate the routing configuration.
For example:
public class BookController : ApiController{
//where author is a letter(a-Z) with a minimum of 5 character and 10 max.
[Route("html/{id}/{newAuthor:alpha:length(5,10)}")]
public Book Get(int id, string newAuthor){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
[Route("json/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
public Book Get(int id, string newAuthor, string title){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
...
Thanks to the Dalorzo answer i did find the problem:
The problem occurred because my application was created the following way:
which resulted in creation of both files, RouteConfig.cs (MVC) and WebApiConfig.cs (WEB API):
What is WRONG is that the code in the question is from RouteConfig.cs
After putting the code
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{action}/{controller}",
defaults: new
{
action = "html"
}
);
in WebApiConfig.cs, it worked proper way.
I am developing a website with ASP.net MVC3.
I have built it up and ran normally at local. Then when I deploy it with IIS 7.5, the site can display. All functionality works except the url is not changing when I switch in between actions and controllers(the url always shows "www.mysite.com" not "www.mysite.com/home/action"). Also, the title of pages are not shown. Instead of my slogan, it shows the domain url like www.mysite.com on the page title of browsers.
I followed the official deploy instruction of ASP.net with IIS.
Is there anyone knows what's the problem? Thanks in advance.
Here is my code for the Global.asax
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ImageWall", // Route name
"ImageWall/{action}/{id}", // URL with parameters
new { controller = "ImageWall", 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
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Regards the title, in your views, do you use something like
ViewBag.Title = "Some Title"
In the HTML source of a page on your site, does the <title> element get populated? If not, then that could explain why you do not see the title.
Regards the url, can you post the code of your global.asax.cs file please (or global.asax.vb if you're using VB.NET). That is where route configuration can take place, so seeing that could help us explain why the url does not a show.
I have found the problem.
The problem is caused by the settings of Domain.com. As I am a fresher to deploy, I didn't set the "A Record" for all my domains. I just set the redirection to my IP.
I just spent time tonight converting an existing ASP.NET webform app to MVC3 using this guide. However, when I go to start the app just to running the app locally to check my work, I'm getting this error:
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:4.0.30319; ASP.NET Version:4.0.30319.237
I've tried setting various breakpoints in my global.asax as I suspected I screwed something up with the routing but the breakpoints aren't hit at all. Since it's not hitting my breakpoints in this file then my assumption is that I don't need to both looking at the Controller or View since that's further down the execution path.
My folder structure contains the following folders and files:
Controllers\
HomeController.cs
Models\
Views\
Home\
Index.cshtml
Shared\
_Layout.cshtml
Error.cshtml
_ViewStart.html
Global.asax
web.config
web.config
Here's the contents of the global.asax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace www
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//ignore aspx pages (web forms take care of these)
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index"}
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
\Controllers\HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace www.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
I'm relatively new to ASP.NET MVC and Visual studio so not sure where to begin debugging this. Any tips would be appreciated.
Based on a reply by Mystere Man, the answer was that global.asax was mistakenly put under the \Views\ folder and not in the root. Once I moved it, all was well.
In my ASP.NET MVC3 App I try simulate "routes.IgnoreRoute("...")"
I create CustomMvcRouteHandler:
public class CustomMvcRouteHandler: MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
// do something
....
return base.GetHttpHandler(requestContext);
}
}
in my Global.asax.cs file i have:
protected void Application_Start()
{
// ............
RegisterRoutes(RouteTable.Routes);
// ............
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("elmah.axd");
//routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new CustomMvcRouteHandler();
}
How can I do this ?
I'm not entirely sure what you mean in your question, but I'll try to answer it...
To simulate an IgnoreRoute all you need to do is associate an instance of the StopRoutingHandler from your route. If you're using the built-in ASP.NET "Route" class then you would do something like this:
routes.MapRoute(
"Ignore-This", // Route name
"ignore/{this}/{pattern}" // URL with parameters
).RouteHandler = new StopRoutingHandler();
Anything that matches that pattern will cause the routing system to immediately stop processing any more routes.
If you want to write your own custom route (for example, a new route type that derives from RouteBase), then from its GetRouteData method you need to return the StopRoutingHandler.
#Eilon is the correct answer. Here is an alternative syntax that feels more MVCish.
routes.Add("Ignore-This",
new Route(
"ignore/{this}/{pattern}",
new StopRoutingHandler())
);