namespace changing in ASP.net MVC [duplicate] - asp.net-mvc

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.

Related

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.

HTTP 404 Error When starting ASP.Net Application using MVC 2

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.)

Does ASP.NET MVC create default routes for areas

I have a couple of areas in my MVC 3 application Auth and Users. I am using Phil Haacks Route Debugging tool to view a list of my routes and see which one gets selected based on my url.
However there are a couple of routes present that I have not created in either my AreaRegistration file or Globalasax and I don’t know where they have come from or how to get rid of them. The routes are highlighted in yellow below.
You can also see that I have created a default route in my Auth area (highlighted in green) which simply points to the Login action of my Auth controller. I have debugged the RouteTable and it gets added when the AreaRegistration.RegisterAllAreas(); method is called. However it does not get added in the AreaRegistration as have stepped through this also.
Does ASP.NET MVC add this as a default and if so can I remove it somehow?
I don’t like to answer my own question but after a day of trying to solve this problem I thought I would post the answer in case anyone else has the same issue.
In the end I got rid of all my areas from my application and just had the basic Global.asax routing. When I ran the app I could see in the route debugger that the routing collection was still being populated with the routes from now non existing areas. After trying many things including deleting everything from my ASP.NET temp files, messing around with IIS AppPools and cleaning out browser data I finally came across the answer.
I deleted everything from the websites bin folder, did a rebuild and low and behold, the routes were gone. I reinstated my areas with the config described and everything is working as it should.
I have no idea why my MVC app was holding onto and populating the old routes but as soon as my bin was cleared and new dll’s created everything worked as it should. If anybody out there knows why this may be then I would be very interested.
Yes, each area has it's own AreaRegistration file that defines area routes. Look for it in your area root folder.
For your User area, look in Areas -> User -> UserAreaRegistration.cs
It should contain something like this:
public class UserAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "User";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"User_default",
"User/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
Did you rename your project? It loads the routes by reflection, probably by scanning everything in the bin folder. So if you refactored your code and changed the assembly name, you could have easily had old code being picked up and registering those routes.
JB

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 in Azure

I have an Azure Web Role project that was recently MVC'd by another developer. According to the developer the app works with no problem when run on it's own (i.e. as a simple web app). However, when I try to run it in the context of the Azure cloud service, I'm seeing a number of 404 errors. I suspect something is not quite right with the routing. Here's an abbreviated version of the current RegisterRoutes method that's part of Global.asax.cs:
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{Services}/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Configuration",
"Configuration",
new { controller = "Configuration", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Account", action = "Index", id = "" }
);}
When the app starts up, the correct view from the Account controller's Index action is displayed. However if I try to navigate to Configuration I get a 404. Converesly if I change the method to this:
public static void RegisterRoutes(RouteCollection routes){
routes.IgnoreRoute("{Services}/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Account",
"Account",
new { controller = "Account", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Configuration", action = "Index", id = "" }
);}
I get the correct view from the Configuration controller's Index action, but I can't navigate to the Account view.
I'm guessing this is a simple problem to solve, but not knowing what exactly was done to "MVC" the Azure app and being new to MVC has me beating my head into the wall.
Here's the configuration of the machine where I'm encountering this issue:
Windows 7 Ultimate with IIS 7.0
Visual Studio 2008 SP1
ASP.NET MVC 1.0
Windows Azure SDK 1.0
Thoughts?
Try using my Routing Debugger. It can help you understand what's going on. http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx
It's weird that the behavior would be different locally than in Azure. Also, you should post your controller code (remove the contents of the action methods, we just need to see the method signatures).
If I had to make a wild guess, I'd guess your Configuration route (in the first example you gave) needs to add id="" in the defaults section.
Haacked: Thanks for pointing me to the debugger. That helped me hunt down the issue in a matter of minutes.
The answer was much simpler than I thought. It all had to do with the following line of code:
routes.IgnoreRoute("{Services}/{*pathInfo}");
I put this line in to help resolve an issue I was having with ASP.NET MVC and WCF RIA Services (more info on that here). The curly braces shouldn't be there. I don't want to replace Services. The code should look like this:
routes.IgnoreRoute("Services/{*pathInfo}");
You can read a full write-up here.
I don't think this is your problem, but you might verify that the System.Web.Mvc reference has its Copy Local = true.

Resources