I am following the tutorial from this site here. Everything was going fine until I added the css and image folder. after adding these two things and running my project, I got the following error:
. I have two controller classes and one view class. If you guys want, I can share them with you. But if you also click on the link I provided, you can see the code there as well. Thanks for your time and help.
Here's my global.asax file:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcMovieStore
{
// 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(
"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();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(#"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
check the code-behind file, global.asax.cs, the namespace should be MvcMovieStore, and the class name should be MvcApplication, I guess the class name doesn't match.
THis is wiered but I did not do anything, I simply ran it again and it worked. Amazing.
I got the same error for no particular reason. Simply close and re-open Visual Studio has fixed my problem.
I found that changing the Namespace on the project, without refactoring that across the whole solution was my problem. Check your project Properties and see what your namespace is, ensure that lines up, across the board.
Related
I have been working on a project and I left it for about one week,when I came back to it and I tried to run the project with Ctr+F5 , it redirect to a URL which is not defined in route config. like this http://localhost:53771/Views/Home/Index.cshtml and confronted with HTTP 404: not found Error. while my route config is like this BUT IT WORKS FINE IF I TYPE THE CORRET URL MYSELF in front of the r+F5 , it redirect to a URL which is not defined in route config. like this http://localhost:53771
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I started debugging the project and it seems the project never come to my HomeController . I just have one controller named Home, and when I removed all the codes of my Home controller it still act the same. and the other thing which it seems wrong, it creates the URL http://localhost:53771/Views/Home/Index.cshtml even before it comes to RegisterRoutes function. the problem is all local and here is my global.asax if needed. I appreciate any help
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace ML_Projectname
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Powered-By");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
HttpContext.Current.Response.Headers.Remove("Server");
}
}
}
I don't believe there is any issue with your routing or your application. Visual Studio's default start action (view by right clicking project -> selecting properties -> selecting Web) is "Current Page". If you're viewing a razor view (such as your /Views/Home/Index.cshtml) at the time you run the project in visual studio, visual studio will try to navigate to this resource directly. Directly requesting a razor view is not valid in the context of an MVC application and you end up seeing the 404 error.
To avoid this, you can set the start url to a specific URL (ex: http://localhost:53771) or even simpler, open and view one of the server side files (ex: HomeController.cs) before running your project via Visual Studio.
tldr version: this is an issue with a setting you have in visual studio, not an issue with your application code
In my ASP.NET MVC 5 application, I used to have a controller called Alpha, which I played around with for a while, and then ended up deleting it. Now, I've decided that I want to have another controller called Alpha, with different functionality from before.
So, I have added a new controller, named it Alpha, and added an Index view for this controller. But when I go to localhost:IP/Alpha, I get the following error:
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
All I have done though, is add the controller with the code, and then add an Index view with the default code.
The strange thing, is that if I add a controller and a view in the same way, but call it anything other than Alpha, then the application works as would be expected, and Alpha's Index view is displayed.
So I am assuming there is something remaining in the system from the old Alpha controller (which may have originally been buggy, I cannot remember), which is conflicting with this new Alpha. Any ideas on how I might investigate this further?
As requested by Jason Evans, here is my Global.asax.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Poseidon
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
As requested by Jason Evans, here is my RoutConfig::RegisterRoutes function:
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 }
);
}
On an MVC 5 with Web API I have the following, using only Attribute Routes:
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); // TODO: Check for Apple Icons
RouteTable.Routes.MapMvcAttributeRoutes();
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
AreaRegistration.RegisterAllAreas();
In the RouteTable all the MVC routes were created ... But not the API ones ...
I checked the RouteTable.Routes and I see an exception:
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at
System.Web.Http.Routing.RouteCollectionRoute.GetEnumerator() at
System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
For testing this I added only two Web Api actions to the project:
[RoutePrefix("api")]
public class StatApiController : ApiController {
[Route("stats/notescreateddaily"), HttpGet]
public IHttpActionResult NotesCreatedDaily() {
// Some code
}
[Route("stats/userscreateddaily"), HttpGet]
public IHttpActionResult UsersCreatedDaily() {
// Some code
}
}
Am I missing something?
Thank You,
Miguel
The solution is in fact replacing:
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
By:
GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
That was a change in Web API 2.
The solution is to call GlobalConfiguration.Configuration.EnsureInitialized(); after all your Web API related configuration is done, but I am curious as to why your registrations look like this...What kind of project template did you use to create the MVC5 project?...The predefined templates that come with Visual Studio has a structure which helps minimize route ordering problems and so would recommend using them, so wondering why your configuration structure looks like that...
I am having the same problem after I upgrade all my web services project using ASP.Net Web API 4.0 to 4.5 and using Web API 2.2 with Cors library. I managed to successfully solve the problem. What I did was eliminating or commenting out the following statement at the RouteConfig.cs file at App_Start folder:`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace myNameSpace.Configurations
{
public static class RouteConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
//DON'T USE THIS. IT WILL GIVE PROBLEMS IN INSTANTIATION OF OBJECTS
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LocationData",
routeTemplate: "dataservices/locations/{controller}/{action}/{id}",
defaults: new {action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ProfileData",
routeTemplate: "dataservices/profiles/{controller}/{action}/{id}",
defaults: new { action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
On my Global.asax.cs file I am using the old routing registration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net.Http.Formatting;
using myNameSpace.IoC;
using myNameSpace.Configurations; // Here actually I change the protected void Application_Start() to protected void Configuration() and change the folder to configuration instead on App_Start
using myNameSpace.Controllers.ExceptionSchema;
using myNameSpace.Filters.HttpFilters;
namespace myNameSpace
{
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterApis(HttpConfiguration config)
{
config.Filters.Add(new CustomHttpExceptionFilter());
}
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
RegisterApis(GlobalConfiguration.Configuration);
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.Register(GlobalConfiguration.Configuration);
}
}
}
Here is the reason:
Attribute Routing in Web API 2
Note: Migrating From Web API 1
Prior to Web API 2, the Web API project templates generated code like this:
protected void Application_Start()
{
// WARNING - Not compatible with attribute routing.
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
If attribute routing is enabled, this code will throw an exception. If you upgrade an existing Web API project to use attribute routing, make sure to update this configuration code to the following:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}
I am using the old route and I decided not to use attribute routing. So take OUT THAT statement
I am new in Asp.net MVC. I am struck at my Customize URL Routing problem.
I have created my Controller named "Customer" and action as "DisplayCustomer".
In Global.asax.cs page,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
// 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 RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Customer",
action = "DisplayCustomer",
id = UrlParameter.Optional
}); // Parameter defaults//, new { Code = #"\d{1001,1002}" }
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
}
I don't know what wrong in it,it is always showing
as
http://localhost:50415/Views/Customer/DisplayCustomer.aspx
not as
http://localhost:50415/Customer/DisplayCustomer
Am I missing something to make it this to work?
Replicated your problem
Select Project Properties
Select Web Tab
Now, See the highlighted part in screen shot below
Original Version
Modified Version
Removed the View Directory and .cshtml extension. This happened because you set the start Page.
Selecting the Current Page will fix your issue
This url: http://localhost:50415/Views/Customer/DisplayCustomer.aspx is probably opening up in your Browser when you run/debug your project while the current active document in Visual Studio is the DisplayCustomer view, try to close this document and re-run the project (i think the problem is fixed for MVC 4 projects).
More importantly, your Routes are not correctly defined. if you want to access your Action using the default pattern ({Controller}/{Action} and in your case /Customer/DisplayCustomer) you don't have to write any custom route, just leave the default route as is:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL pattern
new { Id = UrlParamter.Optional });
Now, the standard way to get the Url pointing to your Action (from within your Controller/View) is to use the Url.Action method. for example: Url.Action("DisplayCustomer", "Customer").
Change "Views" to "Default"
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Customer",
action = "DisplayCustomer",
id = UrlParameter.Optional
}); // Parameter defaults
}
So I've been spending some time with ASP.NET MVC 2 (currently stuck with using Visual Studio 2008) and have now moved onto using Ninject 2.2 and its MVC integration. I've downloaded Ninject 2.2 and Ninject.Web.Mvc from the following locations:
https://github.com/downloads/ninject/ninject/Ninject-2.2.0.0-release-net-3.5.zip
https://github.com/downloads/ninject/ninject.web.mvc/Ninject.Web.Mvc2-2.2.0.0-release-net-3.5.zip
And referenced them in my MVC 2 project. My Global.asax.cs file looks like this (pretty much what the Ninject.Web.Mvc README says):
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;
namespace Mvc2 {
public class MvcApplication : NinjectHttpApplication {
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
);
}
protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo>();
return kernel;
}
}
}
And a home controller that looks like this:
using System;
using System.Web;
using System.Web.Mvc;
namespace Mvc2.Controllers {
public class HomeController : Controller {
private readonly IFoo foo;
public HomeController(IFoo foo) {
this.foo = foo;
}
public ActionResult Index() {
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
}
Now every time I run my project and visit '/' I get a yellow screen of death with a message that says "No parameterless constructor defined for this object." It seems Ninject is not resolving my Foo service and injecting it into HomeController. I imagine I'm missing something really obvious but I'm just not seeing it.
How do I get Ninject to inject Foo into the HomeController, and without using Ninject attributes?
Me: Could you provide a little more information about the IFoo service implementation? Does it have all of its own dependencies satisfied?
Myself: Hmm, no it doesn't. Turns out I didn't bind its dependencies. Boy, is that error message and stack trace misleading!
So my mistake was that I didn't bind one of the dependencies of the IFoo implementation and so Ninject failed silently and tried to continue on its merry way. Which is really unfortunate because it could lead to some really strange behavior once I deviate from a trivial setup. I guess my next question should be how can I get Ninject to fail as early as possible and provide good messaging about what's wrong? But for now I can at least get on with it.