HTTP 404 Error When starting ASP.Net Application using MVC 2 - asp.net-mvc

I am having problems trying to get a very simple ASP.Net application to start using .Net Framework 4 and MVC 2.
When press F5 in Visual Studio 2010, I get the following error message HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unable. Please review the following URL and make sure it is spelled correctly.
When I added the view, I added the view by right clicking on the method in the controller, and this of course added the view. I have also noticed that when selecting "Go to View", that this too throws an error in Visual Studio and says that the view does not exist! Further, I have gone to the Global.asax page and changed the default controller to be that of the one I have added, but this has made NO difference.
So, please tell me - but do I need to change?

Try to go to /ControllerName/ActionName. If you have changed the default, you have to make sure you have spelled it correctly. Also note that the ASP.NET MVC Framework removes the "Controller" suffix of controller names.
If your new controller is called MyNewController it should:
Inherit from Controller
Be called MyNewController
Like this
public MyNewController : Controller {
public ActionsResult MyAction() {
return View();
}
}
In Global.asax.cs for this case, the default settings counld be:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "MyNew", action = "MyAction" }
);
Note how the default controller setting lacks the "Controller" suffix.

To install MVC some considerations need to be take in account.
I think you are trying to install it on IIS 5 or 6
Please read this article
http://blog.stevensanderson.com/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
or upgrade to IIS 7

Had a similar problem. I had made the mistake of modifying the default route from this:
url: "{controller}/{action}/{id}",
To this:
url: "{controller}/{action}/{id*}",
Placing the asterisk in the wrong place caused absolutely every URL to give me a 404 - and as usual ASP.Net routes are practically impossible to debug.
The solution was placing the asterisk in the proper place:
url: "{controller}/{action}/{*id}",
(This allows routes with as many forward slashes as you like, instead of limiting them to 3. The portion with an asterisk is a catchall.)

Related

namespace changing in ASP.net MVC [duplicate]

I currently have two unrelated MVC3 projects hosted online.
One works fine, the other doesn't work, giving me the error:
Multiple types were found that match the controller named 'Home'. This
can happen if the route that services this request
('{controller}/{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 way my hoster works is that he gives me FTP access and in that folder I have two other folder, one for each of my applications.
ftpFolderA2/foo.com
ftpFolderA2/bar.com
foo.com works fine, I publish my application to my local file system then FTP the contents and it works.
When I upload and try to run bar.com, the issue above fires and prevents me from using my site. All while foo.com still works.
Is bar.com searching from controllers EVERYWHERE inside of ftpFolderA2 and that's why it's finding another HomeController? How can I tell it to only look in the Controller folder as it should?
Facts:
Not using areas. These are two COMPLETELY unrelated projects. I place each published project into each respective folder. Nothing fancy.
Each project only has 1 HomeController.
Can someone confirm this is the problem?
Here is another scenario where you might confront this error. If you rename your project so that the file name of the assembly changes, it's possible for you to have two versions of your ASP.NET assembly, which will reproduce this error.
The solution is to go to your bin folder and delete the old dlls. (I tried "Rebuild Project", but that didn't delete 'em, so do make sure to check bin to ensure they're gone)
This error message often happens when you use areas and you have the same controller name inside the area and the root. For example you have the two:
~/Controllers/HomeController.cs
~/Areas/Admin/Controllers/HomeController.cs
In order to resolve this issue (as the error message suggests you), you could use namespaces when declaring your routes. So in the main route definition in Global.asax:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "AppName.Controllers" }
);
and in your ~/Areas/Admin/AdminAreaRegistration.cs:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "AppName.Areas.Admin.Controllers" }
);
If you are not using areas it seems that your both applications are hosted inside the same ASP.NET application and conflicts occur because you have the same controllers defined in different namespaces. You will have to configure IIS to host those two as separate ASP.NET applications if you want to avoid such kind of conflicts. Ask your hosting provider for this if you don't have access to the server.
In MVC4 & MVC5 It is little bit different, use following
/App_Start/RouteConfig.cs
namespace MyNamespace
{
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 },
namespaces: new[] {"MyNamespace.Controllers"}
);
}
}
}
and in Areas
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MyNamespace.Areas.Admin.Controllers" }
);
Watch this... http://www.asp.net/mvc/videos/mvc-2/how-do-i/aspnet-mvc-2-areas
Then this picture (hope u like my drawings)
in your project bin/ folder
make sure that you have only your PROJECT_PACKAGENAME.DLL
and remove ANOTHER_PROJECT_PACKAGENAME.DLL
that might appear here by mistake or you just rename your project
What others said is correct but for those who still face the same problem:
In my case it happened because I copied another project n renamed it to something else BUT previous output files in bin folder were still there... And unfortunately, hitting Build -> Clean Solution after renaming the project and its Namespaces doesn't remove them... so deleting them manually solved my problem!
Check the bin folder if there is another dll file that may have conflict the homeController class.
Another solution is to register a default namespace with ControllerBuilder. Since we had lots of routes in our main application and only a single generic route in our areas (where we were already specifying a namespace), we found this to be the easiest solution:
ControllerBuilder.Current
.DefaultNamespaces.Add("YourApp.Controllers");
Even though you are not using areas, you can still specify in your RouteMap which namespace to use
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new[] { "NameSpace.OfYour.Controllers" }
);
But it sounds like the actual issue is the way your two apps are set up in IIS
I just had this issue, but only when I published to my website, on my local debug it ran fine. I found I had to use the FTP from my webhost and go into my publish dir and delete the files in the BIN folder, deleting them locally did nothing when I published.
if you want to resolve it automatically.. you can use the application assambly
just add the following code:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { string.Format("{0}.Controllers", BuildManager.GetGlobalAsaxType().BaseType.Assembly.GetName().Name) }
);
There might be another case with Areas even you have followed all steps in routing in Areas(like giving Namespaces in global routing table), which is:
You might not have wrapped your Global Controller(s) in 'namespace'
you provided in routing.
Eg:
Done this:
public class HomeController : Controller
{
Instead of:
namespace GivenNamespace.Controllers
{
public class HomeController : Controller
{
You can also get the 500 error if you add your own assembly that contains the ApiController by overriding GetAssemblies of the DefaultAssembliesResolver and it is already in the array from base.GetAssemblies()
Case in point:
public class MyAssembliesResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
var baseAssemblies = base.GetAssemblies();
var assemblies = new List<Assembly>(baseAssemblies);
assemblies.Add(Assembly.GetAssembly(typeof(MyAssembliesResolver)));
return new List<Assembly>(assemblies);
}
}
if the above code is in the same assembly as your Controller, that assembly will be in the list twice and will generate a 500 error since the Web API doesn't know which one to use.
In Route.config
namespaces: new[] { "Appname.Controllers" }
Got same trouble and nothing helped. The problem is that I actually haven't any duplicates, this error appears after switching project namespace from MyCuteProject to MyCuteProject.Web.
In the end I realized that source of error is a global.asax file — XML markup, not .cs-codebehind. Check namespace in it — that's helped me.
i just deleted folder 'Bin' from server and copy my bin to server, and my problem solved.
Some time in a single application this Issue also come In that case select these checkbox when you publish your application
We found that we got this error when there was a conflict in our build that showed up as a warning.
We did not get the detail until we increased the Visual Studio -> Tools -> Options -> Projects and Solutions -> Build and Run -> MSBuild project build output verbosity to Detailed.
Our project is a .net v4 web application and there was a conflict was between System.Net.Http (v2.0.0.0) and System.Net.Http (v4.0.0.0). Our project referenced the v2 version of the file from a package (included using nuget). When we removed the reference and added a reference to the v4 version then the build worked (without warnings) and the error was fixed.
Other variation of this error is when you use resharper and you use some "auto" refactor options that include namespace name changing. This is what happen to me. To solve issue with this kind of scenario delete folderbin
Right click the project and select clean the project. Or else completely empty the bin directory and then re-build again. This should clear of any left over assemblies from previous builds
If it could help other, I've also face this error.
The problem was cause by on incorrect reference in me web site.
For unknown reason my web site was referring another web site, in the same solution.
And once I remove that bad reference, thing began to work properly.
If you're working in Episerver, or another MVC-based CMS, you may find that that particular controller name has already been claimed.
This happened to me when attempting to create a controller called FileUpload.
i was facing the similar issue. and main reason was that i had the same controller in two different Area. once i remove the one of them its working fine.
i have it will helpful for you.
I have two Project in one Solution with Same Controller Name. I Removed second Project Reference in first Project and Issue is Resolved
I have found this error can occur with traditional ASP.NET website when you create the Controller in non App_Code directory (sometimes Visual Studio prevents this).
It sets the file type to "Compile" whereas any code added to "App_Code" is set to "Content". If you copy or move the file into App_Code then it is still set as "Compile".
I suspect it has something to with Website Project operation as website projects do not have any build operation.Clearing the bin folder and changing to "Content" seems to fix it.

MVC view throwing 500.19 error when using the direct url, but not when routed via the controller?

I have two views in my mvc application. They are both stored within area, A, and within folder, home.
I recently was changing the properties of my project and it asked to reconfigure my site configs in iis as always I clicked yes. Since then I have been getting a 500.19 error saying that my configuration file has incorrect data.
At this point I was thoroughly confused. I compared my web.configs against other application web.configs and there really was no difference. So, I then changed my routing so that inputting this. :
http://stackoverflow/myarea/home
Actually returns my view of. :
http://stackoverflow/myarea/home/index
So, when I just input. :
http://stackoverflow/myarea/home/index => this errors with 500.19
but when I use. :
http://stackoverflow/myarea/home => this works with no error but brings up the same view as the above would
I have tried a lot of things blowing away my application in iis and recreating it, numerous iis resets, deleting my view and recreating it. Nothing has came close to working.
Now what is really odd is I have another view in the same folder. :
http://stackoverflow/myarea/home/myotherview
When I go directly to this url above it works perfectly no issues, no 500.19.
So, it is as if something is tying my one view to this issue. I know that this is an odd one, but I am lost on what to try next. Hoping someone has seen something like this before. I know a 500.19 is usually an issue within the web.config, but after the other page works I think it is some sort of setting I am just unaware of.
500.19 is a configuration issue.
See here http://blogs.msdn.com/b/webtopics/archive/2010/03/08/troubleshooting-http-500-19-errors-in-iis-7.aspx
I suspect that you do not have the routes in the global.asax or in the areas registration asax file setup properly. Without seeing your routes I cannot help you more specifically. But you might need to setup something like this in
public static void RegisterRoutes(RouteCollection routes)
routes.MapRoute(
"DefaultIndexRoute",
"{controller}/{action}/{id}",
new {controller = "Home", action="Index", id=UrlParameter.Optional}
);
}
in the AreaRegistrations.asax file it will be
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"DefaulAreatIndexRoute",
"MyArea/{controller}/{action}/{id}",
new {controller = "Home", action="Index", id=UrlParameter.Optional},
new [] {"My.Area.Namespace.Controllers"} // optional namespace in case there is a conflict
);
}
this is a catch-all kind of route. MVC will choose your route based on the first one that matches. So you will want this at the bottom of the list most likely. With more specific routes specified above it.
Basically if mvc cannot find an adequate route it will throw it back to IIS to figure out in which you will most likely get an error.
Please post your route configs so we can help you a bit more. Thanks.

Why am I getting HTTP 404 on all controllers I copied into a new MVC4 project?

I created a new MVC4 project, as I had messed around with too many default, templated content in the one I was working on. I set Authentication to 'None', and copied quite a few components, e.g. controllers, base classes, view models, validators (Fluent Validation) etc. over. I kept the original Home controller and view.
That original Home page, through its Index action, is all that works. All my 'imported' controllers derive from ComairRIController, while Home doesn't, but I even tried removing this inheritance from one of my controllers and just inheriting from Controller, just like Home, with no effect; I still get the 404.
The project builds with no errors or warnings at all and runs fine opening the Home/Index view. What could be wrong here? How can I diagnose this? The constructor for my ComairRIController doesn't even get invoked, so the request isn't getting very far at all.
I am using the default route configuration:
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 }
);
}
IMPORTANT INFORMATION: Both the source project (pure MVC4) and destination project (Orchard module) have exactly the same names, and default namespaces. I intentionally did this to avoid as many namespace mismatches as possible.
NEW INFORMATION: I have added Elmah 2.0.2 via NuGet, and set it up to log to XML files. It logs an error for each 404, the error being (I have omitted the stack trace for brevity):
<error errorId="db2b4236-b913-4b98-878e-f3e02fdff321"
application="/"
host="7F3KH5J"
type="System.Web.HttpException" \
message="The controller for path '/ApplicantProfile/Start' was not found or does not implement IController."
source="System.Web.Mvc"
detail="System.Web.HttpException (0x80004005): The controller for path '/ApplicantProfile/Start' was not found or does not implement IController.
Interestingly, requests for Elmah.axd also return a 404.
You mentioned that you copied over a few components from an existing project, but didn't mention whether or not you copied over the Views for anything except the Home/Index action.
Could it be there's no matching view for any of your other Controllers?

The view 'Index' or its master was not found.

The view 'Index' or its master was not found. The following locations were searched:
~/Views/ControllerName/Index.aspx
~/Views/ControllerName/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
I got this error when using ASP.Net mvc area. The area controller action are invoked, but it seems to look for the view in the 'base' project views instead of in the area views folder.
What you need to do is set a token to your area name:
for instance:
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
).DataTokens.Add("area", "YOURAREANAME");
This error was raised because your Controller method name is not same as the View's name.
If you right click on your controller method and select Go To View (Ctrl+M,Ctrl+G), it will either open a View (success) or complain that it couldn't find one (what you're seeing).
Corresponding Controllers and View folders name have the same names.
Corresponding Controller methods & Views pages should same have the same names.
If your method name is different than view name, return view("viewName") in the method.
Global.asax file contain the URL Route.
Default URL route like this.
"{controller}/{action}/{id}"
So,Try this.
1. Right click your controller method as below.
Example: let say we call Index() method.Right click on it.
2. Click Add View.. and give appropriate name.In this example name should be Index.
Then it will add correct View by creating with relevant folder structure.
Check the generated code at MyAreaAreaRegistration.cs and make sure that the controller parameter is set to your default controller, otherwise the controller will be called bot for some reason ASP.NET MVC won't search for the views at the area folder
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
);
}
Where this error only occurs when deployed to a web server then the issue could be because the views are not being deployed correctly.
An example of how this can happen is if the build action for the views is set to None rather than Content.
A way to check that the views are deployed correctly is to navigate to the physical path for the site on the web server and confirm that the views are present.
The problem was that I used MvcRoute.MappUrl from MvcContrib to route the context.Routes.
It seems that MvcContrib routing mapper was uncomfortable with area routing.
You most likely did not create your own view engine.
The default view engine looks for the views in ~/Views/[Controller]/ and ~/Views/Shared/.
You need to create your own view engine to make sure the views are searched in area views folder.
Take a look this post by Phil Haack.
I had this problem today with a simple out of the box VS 2013 MVC 5 project deployed manually to my local instance of IIS on Windows 8. It turned out that the App Pool being used did not have the proper access to the application (folders, etc.). After resetting my App Pool identity, it worked fine.
right click in index() method from your controller
then click on goto view
if this action open index.cshtml?
Your problem is the IIS pool is not have permission to access the physical path of the view.
you can test it by giving permission. for example :- go to c:\inetpub\wwwroot\yourweb then right click on yourweb folder -> property ->security and add group name everyone and allow full control to your site . hope this fix your problem.
It´s still a problem on the Final release.. .when you create the Area from context menu/Add/Area, visual studio dont put the Controller inside de last argument of the MapRoute method. You need to take care of it, and in my case, I have to put it manually every time I create a new Area.
You can get this error even with all the correct MapRoutes in your area registration. Try adding this line to your controller action:
If Not ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
ControllerContext.RouteData.DataTokens.Add("area", "MyAreaName")
End If
If You can get this error even with all the correct MapRoutes in your area registration and all other basic configurations are fine.
This is the situation:
I have used below mentioned code from Jquery file to post back data and then load a view from controller action method.
$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'});
Above jQuery code I didn't mentioned success callback function.
What was happened there is after finishing a post back scenario on action method, without routing to my expected view it came back to Jquery side and gave view not found error as above.
Then I gave a solution like below and its working without any problem.
$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'},
function (data) {
var url = Sys.Url.route('PetDetail', { action: "ReturnRetailOnlySalesItems", controller: "Customers",petKey: '<%: Model.PetKey %>'});
window.location = url;});
Note: I sent my request inside the success callback function to my expected views action method.Then view engine found a relevant area's view file and load correctly.
I have had this problem too; I noticed that I missed to include the view page inside the folder that's name is same with the controller.
Controller: adminController
View->Admin->view1.cshtml
(It was View->view1.cshtml)(there was no folder: Admin)
This error can also surface if your MSI installer failed to actually deploy the file.
In my case this happened because I converted the .aspx files to .cshtml files and visual studio thought these were brand new files and set the build action to none instead of content.
I got the same problem in here, and guess what.... looking at the csproj's xml' structure, I noticed the Content node (inside ItemGroup node) was as "none"... not sure why but that was the reason I was getting the same error, just edited that to "Content" as the others, and it's working.
Hope that helps
Add the following code in the Application_Start() method inside your project:
ViewEngines.Engines.Add(new RazorViewEngine());
I added viewlocationformat to RazorViewEngine and worked for me.
ViewLocationFormats = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Areas/Admin/Views/{1}/{0}.cshtml",
"~/Areas/Admin/Views/Shared/{0}.cshtml"
};

ASP.NET MVC Routing Questions

I just started using ASP.NET MVC and I have two routing questions.
How do I set up the following routes
in ASP.NET MVC?
domain.com/about-us/
domain.com/contact-us/
domain.com/staff-bios/
I don't want to have a controller specified in the actual url in order to keep the urls shorter. If the urls looked liked this:
domain.com/company/about-us/
domain.com/company/contact-us/
domain.com/company/staff-bios/
it would make more sense to me as I can add a CompanyController and have ActionResults setup for about-us, contact-us, staff-bios and return appropriate views. What am I missing?
What purpose does the name "Default" name have in the default routing rule in Global.asax? Is it used for anything?
Thank you!
I'll answer your second question first - the "Default" is just a name for the route. This can be used if you ever need to refer to a route by name, such as when you want to do URL generation from a route.
Now, for the URLs that you want to set up, you can bypass the controller parameter as long as you're ok with always specifying the same controller as a default. The route might simply look like this:
{action}/{page}
Make sure that it's declared after your other routes, because this will match a lot of URLs that you don't intend to, so you want the other routes to have a crack at it first. Set it up like so:
routes.MapRoute(null, "{action}/{page}",
new { controller = "CompanyController", action = "Company", page = "contact-us" } );
Of course your action method "Company" in your MyDefault controller would need to have a "string page" parameter, but this should do the trick for you. Your Company method would simply check to see if the View existed for whatever the page parameter was, return a 404 if it didn't, or return the View if it did.
Speaking of setting up routes and Phil Haack, I have found his Route Debugger to be invaluable. It's a great tool for when you don't understand why particular routes are being used in place of others or learning how to set up special routing scenarios (such as the one you've mentioned). It's helped clear up many of the intricacies of route creation for me more than any other resource.
To answer your second question about Global.asax, it an optional file used for responding to application level and session-level events raised by ASP.NET or HTTP modules. The Global.asax file resides in the root directory of the ASP.NET application.If you do not define it assumes you have not defined any application handler or session handler. MVC framework uses the routing engine to which the routing rules are defined in the engine, so as to map incoming URL to the correct controller.
From the controller, you can access the ActionName. If there is no specific controller, it will direct to the default page. The default controller is "Home" with its default action "Index". Refer to MSDN:
http://msdn.microsoft.com/en-us/library/2027ewzw%28v=vs.100%29.aspx
Refer to stackoverflow question
What is global.asax used for?
This is a sample of how a default route should look like
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);

Resources