I have a webforms app, that has some Web Api controllers in it for integrations.
Two are working just fine. But Today I wanted to add another controller.
Should be simple enough, I add a new Web Api controller, add a little bit of code to it, and:
namespace MyApp.Web.App_Code
{
public class AuthExportController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
and when i call it at this url :
http://localhost:30978/MyApp/api/AuthExport
I get this error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Multiple types were found that match the controller named
'AuthExport'. This can happen if the route that services this request
('api/{controller}/{id}') found multiple controllers defined with the same name but
differing namespaces, which is not supported. The request for 'AuthExport' has found
the following matching controllers: MyApp.Web.App_Code.AuthExportController
MyApp.Web.App_Code.AuthExportController</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace> at
System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessag
e request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken)</StackTrace>
</Error>
As you can see, it is complaining about 2 controllers with the same name, but its the exact same controller. My other controllers work fine, just this particular one.
If it helps anything, this is my routing code in global.asax
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
}
Driving me mad!
Update:
Ok I managed to fix it, but I don't understand why, so if someone could explain it to me.
I compared my working controllers with my non working one.
Exact same signatures exactly, nothing different, same using statements, same inheritance etc etc.
One thing I did notice is the build action on the file.
Working file has a build action of "Content" and the non working has a build action of "Compile" . I change my non working one to "Content" and it works.
So now I am even more confused :) Happy that it works, but I don't like black magic in my systems
TL;DR:
Delete bin folder in your project's file directory and build your project again.
Explanation:
I just encountered this error while renaming an existing project and changing namespaces for it and this is what happened:
Let's say projects' name was FirstName and I wanted to rename it to SecondName.
I built project which compiled everything and generated bin/Debug/FirstName.dll files
I renamed the project to SecondName
I refactored the namespace
Built and ran the project
This generated bin/Debug/SecondName.dll
When project was ran, IIS Express simply took all of the .dll files and loaded them into memory, which happened to include both FirstName.dll and SecondName.dll.
As you might already understood, FirstName.dll and SecondName.dll had the same classes and methods, but with a different namespaces!
Therefore, as both of DLLs were loaded into memory by IIS, WebApi routing mechanism was finding both of namespaces with same controllers and action names.
And there you have it. No voodoo magic after all :)
I had to change names of references, projects and solution and after that I had this problem for days.
When I looked for solution, I got the answer everywhere that remove your /bin folder contents and try rebuilding solution, I did that but this didn't solve my problem.I then created a separate solution added all these projects in that solution with bin folder empty, and build the solution still didn't solve my problem.
Here are the things I had to do to get back on track:
First changed assembly names from Project/Properties/
Cleared /bin , /bin/debug folder
Cleared /obj/debug/(.dll, .cache, temporary created files) of each project.
Then rebuild the solution and finally got it solved.
If removing only /bin doesn't work out then try this.
Related
I am trying to work through this tutorial, ASP.Net Core Razor Pages, but (often) when I build the solution, I get a CS0234 error stating that a namespace is missing from file Index.g.cshtml.cd, but where does this file exist?
I have tried
All the build/clean/rebuild solution options.
I have restarted Visual Studio
I have deleted the DEBUG files and restarted VS and FINALLY
I have restarted my PC.
The ONLY solution that seems to work, is to delete the entire solution/project and start again.
Surely there must be a fix for this?
Can you assist?
If an error says a using directive or namespace is missing from xxx.g.cshtml.cs, that usually means, that there is a directive directly in the view (.cshtml or .vbhtml), that the compiler cannot resolve.
In my case I had the following statement in a partial view:
#inject UserManager<AppUser> UserManager
I then went along and refactored the AppUser class from the web application Namespace.Web.AppUser into Namespace.Entities.AppUser, which then was causing that error.
There are different ways to resolve this.
The easiest way is to use a fully qualified type namespace:
#inject UserManager<Namespace.Entities.AppUser> UserManager
And do not forget to add a reference to the other project, if it is in another project.
Or: add a using statement:
#using Namespace.Entities;
Or: Add the using statement above to your ~\Views\_ViewStart.cshtml. This will make that class available in all views.
I landed here with the same errors with Visual Studio 2019 16.2.2. For me, I had changed the name of some of the models and rather than picking up the error in the actual views which were using the models, the error showed in page.g.cshtml rather than page.cshtml.
So, my solution was rather simple. If the error was in page.g.cshtml, ignore the g, go to the view page.cshtml, update the model name to the correct name, rebuild and errors gone.
right click your project and open folder in Explorer. Then search for "Index.g.cshtml.cs"
Then delete the file search results
Make sure your Index.cshtml is referencing the correct model.
Recently I have faced the same issue,
Try the following simple method
copy the error and paste it in the notepad. There you can able to see the original root cause path of the error file, e.g 'YourProjectFolder'\obj\Debug\netcoreapp2.2\Razor\Views\'View Name'\index.g.cshtml.cs
Locate the file, if the error really persists refer the correct namespace in your index.cshtml file else delete the file and rebuild.
Also check you have any duplicate file and which was excluded from the project. If it is exists delete the file too
Now clean and rebuild the project. (You may need to clean, close VS, rebuild)
If your solutions keeps failing because of those .g .cs files, it could be because you forgot to update the namespace of a class that you may have moved, in the actual cshtml file (example via an injection of the said namespace).
This is what solved the issue for me:
https://til.secretgeek.net/.net_core_MVC/error_in_g_cs.html
you can try below solution
Go to C:\Temp\msbuild
2.There you would find folder with your project name and inside those folder you find these files as shown in below image
Try to delete those files and rebuild your solution that might help you
There is actually no real answer to this question.
It turns out that the file is create inside the DEBUG folder.
However, after deleting the Debug folder, I was still getting the error.
So it must be a VS bug?
Try to clean all the obj folders in all of your projects and build again. This is part of the code that is generated by the compiler, sometimes it is not synchronized with the view itself, even Rebuild that should clean everything doesn't work. Do it manually. Hope this helps
It's Microsoft.AspNetCore.Razor.Design Package issue.
I tried with 2.2 version in my VS2017 which does not support this and gives ".g.cshtml not found" in obj directory.
I solved issue as below:
I downgraded ASP.NET Core version of my project 2.2 to 2.1
Changes done in startup.cs:
CompatibilityVersion.Version_2_2 to CompatibilityVersion.Version_2_1
Change all dll of Nuget packages to 2_1 supportive dll
SDK make sure its 2.1.x
and issue resolved.
Add full namespace in _ViewImports
#using Microsoft.AspNetCore.Http
May be my answer is something late, but hopefully it will help someone:
I have faced the dame issue because I have changed the Project name and later I tried to change the namespaces inside controllers and models, then I found out there is a direct mentioning of the namespace inside (Pages/_ViewImports.cshtml) from there I updated them to match the namespace used inside my models and the issues gone. ViewImportsImage
Now my ViewImports.cshtml content looks as follows:
ViewsImport.cshtml content
I have converted one huge Website Project into a Web Application Project as we want to have Compiled code in form of DLL for security purposes and followed below MSDN articles:
http://blogs.msdn.com/b/webdev/archive/2009/10/29/converting-a-web-site-project-to-a-web-application-project.aspx
http://msdn.microsoft.com/en-us/library/aa983476%28v=vs.100%29.aspx
The website is having 1000s of web pages/files. I have resolved all the issues of duplicate references, class name colisions and some compilation errors faced at on Build Solution stage. Due to the earlier website pattern, class names are in the following pattern:
for e.g. if UserMaster is in admin/Operations/Masters folder so the class name will be like: admin_Operations_Masters_UserMaster.
Now, Web Application is Building Successfully and when I try to run the application, it shows "Could Not Load Type 'ClassName'" so I found out that the issue of because Namespaces are absent due to earlier Website Pattern.
Found out in the MSDN:
By default, pages and classes that are built by using the Visual Studio Web site project model do not automatically include a code namespace. However, pages, controls, and classes that are built by using the Visual Studio Web application project model automatically include a code namespace. When converting the Web site project to a Web application project, you will have to add the namespaces to the code.
I have DEFAULT NAMESPACE in the project properties.
So I tried to add the namespaces to whole of the project via ReSharper -> Refactor -> Adjust Namespaces but its for .cs files only and not for .aspx.cs etc AND so its not working.
I thought I need to make a utility to add the namespaces automatically in pages as per their folder path structure but its a time consuming process.
So need a workaround to add the namespaces automatically in pages as per their folder path structure.
Secondly,
What I did for testing is, I have wrapped the default namespace in login page of the project where I faced 'could not load type issue', added in Inherits attribute also. Then did a Clean Solution then Rebuild Solution. But still getting the same issue.
I don't why DLL is not getting updated with the login page's class.
The strange thing is when I change the Codebehind to CodeFile (attribute of Page Directive) then the page is working very fine. Its due to source file is present at the time of running the project BUT i want to use Codebehind attribute as it will tell the compiler to look for the class in DLL not in Source file.
Finally, Summary is :
I have two major issues:
Could not load type 'className'
How to add the namespaces automatically in pages as per their folder path structure.
I have already searched here and came around different topics but nothing works for me. one have suggested to use "Surround With" feature of VS but I need to go one by one on each file which is NOT possible right now.
So Tried:
Set path of DLL to "bin" instead of "bin\debug"
Checked the Build Configuration and its of x86. also the DLL is present in bin
Checked all project properties and all are fine. Cleaned and rebuild solution hundreds of times. Cleaned Temporary ASP.NET files also.
Set Build Action to "Compile" for .cs class files
Cannot set Build action to Compile for aspx pages as they are static html and they should be set to "Content" which is default Build Action.
Resharper solution for adding namespaces but not working
Please help....
Any help will be greatly appreciated. Thanks.
Solved the Issue:
Earlier, I have tried to Set Build Action to "Compile" for .cs class files Only and for all the files sitewide to Compile from .csproj file but it was not working due to aspx page itself set to Compile which was not required.
Now, I have changed the Buid Action to Compile which was Content for .aspx.cs and .aspx.designer.cs files.
and it solved the issue.
Like for e.g.:
Solution 'TestWebApp1'
Project 'TestWebApp1' (ASP.NET Web Application)
Properties
References
App_Data
Scripts
Default.aspx (Build Action: Content)
Default.aspx.cs (Build Action: Compile)
SiteLayout.Master (Build Action: Content)
SiteLayout.Master.cs (Build Action: Compile)
Web.config
Source: None of my "code behind" code is being called
I am using VS2008 and an AddIn to create a web service.
The tool also creates code to access remote procedures (in fact this is another web service).
In the created code some classes are used which will contain the response. So it is a very nice solution.
Now to my problem: When I use 'Goto definition' function, it shows me the class 'extracted from metadata'. So I guess it compiled the class into some library.
Now I would like to know the DLL where the class is defined.
How can this be achieved? To be honest, I manually checked the DLL and either I am getting old or there is some magic in how VS locates classes.
Could someone please give me a kick/hint in the right direction?
Thanks
Ok. I found out myself. It is too easy:
First, I hover the cursor over the tab header and it gives me the location of the DLL. Although this DLL is not part of the project, within the .svc file, the class is known as the declaring DLL is in the bin folder of the web service project.
I find this very strange as I thought that only files being part of the project (i.e. included) or libaries in the GAC are used for name resolving.
Anyway, I learned something new today, which is not part as all.
I am learning Controller rendering in Sitecore from Here .
I created One simple controller(HelloWorld) and Related View(Index.schtml) . Mapped it(with Name PageContent) in rendering section of Sitecore Explorer... and Add Rendering Item in Home Item in Content Section of Sitecore Explorer.. But When I Browse it, it gives the Error .
The controller for path '/' was not found or does not implement IController.
All the post I have Read are related to Asp .Net MVC ..but I have issue related to Sitecore MVC
Sample.html (Page Content in Sitecore Explorer Rendering Section)
#using Sitecore.Mvc
<html>
<body>
#Html.Sitecore().Placeholder("content")
<p>Today's date is #DateTime.Now.ToShortDateString()</p>
</body>
</html>
Only this Line is giving Problem
#Html.Sitecore().Placeholder("content")
If I remove this line ...It Works fine and page on Browser show date and time
Index.html
<p>Hello from Controller -todays Date is #DateTime.Now.ToString()</p>
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HellowWorld/
public ActionResult Index()
{
return View();
}
}
}
This can occur if you have included the default MVC routes, as they override Sitecore's own controller implementation.
Ensure that you have removed the following lines from RouteConfig.cs/Global.cs (depending on MVC version);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Please check the version of System.Web.Mvc.dll referenced by your project. It maybe later than the same dll in Sitecore Website\Bin folder. Please ensure that your project references the same version of System.Web.Mvc.dll as the one in the Website\Bin folder.
FYI. There are two ways to specify the controller function in the ControllerRendering:
By just the controller name. (Please omit the "Controller" suffix in
this case)
By the fully qualified name. For example
"Project.Controllers.HelloWorldController, Project". In this case do not omit the "Controller" suffix.
Something else I would like to add is the following. I was getting the same answer in Sitecore and then I noticed the need for the following item type.
Layout -> Controllers -> [Controller Item Reference Type]
I created each controller item for each controller and that seem to bridge the gap between the controller rendering items in the content tree under Renderings and the actual controller in code. The content of this controller item provides the namespace and dll where the code of the controller is stored and the action which the controller action points to.
I hope this helps. Since using these items, the error has gone away. I am using Sitecore 8.0 by the way in my example.
I faced with the same error in my program. Actually I had a class to render Partial View To string, but I made a terrible mistake and put function parameters incorrectly.
PartialToStringClass.RenderPartialView("ManageEmails", "RecoveryPassword", user);
The first parameter is my contrller name and the second one is my Partial View name.
But I changed their place by mistak.
In addition to Carlos' answer, i also had to add my model in CMS, under Models:
This may be related to the MVC being installed in different places on different servers but changing the 'Application Pool Identity' for the application in IIS to 'LocalSystem' fixed the issue for me. I Recycled the App Pool for the app & Restarted the web service for the app after the change.
---Working Solution---
This error will come because of the different versions of your Sitecore.Web.Mvc.Dll in solution reference folder(Project name->References->Sitecore.Web.Mvc->right click and check properties) and the version of Sitecore.Web.Mvc.Dll in Web.Config in views Folder.
For solving this error you have to make sure that the version of Sitecore.Web.Mvc.Dll is same in both folders.
Thanx.
The Problem in my project was that I was using asp.net mvc 5.2.4 but the default installation from sitecore was using 5.2.3 and in the web.config from my views folder there was the wrong version used and the error was not showing that there is a version missmatch! After downgrading my solution to 5.2.3 it was working.
I found this on another thread. I installed Sitecore 9.1 using the scripts and my web.config within the Views folder does indeed reference 5.2.3 so I tired downgrading my System.Web.Mvc down to 5.2.3 as this suggests and copy/pasting the .dll over to my sc910.sc instance but it didn't fix the issue. Still looking for a solution.
UPDATE
I went through Sitecore 9.1 training, while doing so I encountered the same issue. Turns out I was getting the error because I had not (Visual Studio) published my entire project. After creating a new controller it is required that you rebuild your project otherwise the .dll is not updated and the error will occur. It is recommended that you create a publish profile and then use the publish web button to do this.
Another important thing to point out is, before publishing your project I highly recommend you expand your References, select all of the references, open the properties menu, then set the Copy Local property to False. If you do not do this your .dlls will cause issues if both your wwwroot project and out of wwwroot project do not contain the exact same .dll version, this is causes a pain in the butt scenario. Also, I highly recommend setting the Build Action properties within both your main web.config and the one located within your Views folder to a value of None, if you don't do this you will end up with compilation errors.
I just ran into this issue as well. I resolved it by
Updating the views/web.config to include the a compiler node to point to the DotNetCompilerPlatform type.
Updating the project reference to ensure that the same version of Microsoft.CodeDom.Providers.DotNetCompilerPlatform was output to the bin folder.
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
</compiler>
</compilers>
</system.codedom>
I ran into this error once again. In this more recent case it was because my rendering item's controller field was misspelled. You can use a fully qualified name in the controller field to avoid namespace conflicts. In my case the correct fully qualified name was as follows:
So the first portion is the full namespace path including the controller name followed by a coma then by the project name:
Do make sure that you include the Controller in your website project's proj file... I accidentally left the proj file in my local Excluded Changes so it was working locally but broke with this error when the code reached the test environment. After thinking this was a Sitecore issue for a couple hours I realized that it was much simpler than that for me.
i renamed my namespace for my whole project. Everything is still working fine, but my WebAPI is now finding two routes for my controllers.
Multiple types were found that match the controller named 'department'.
This can happen if the route that services this request ('api/{controller}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported.
The request for 'department' has found the following matching controllers:
A***.P***.Benutzerverwaltung.Jo***MVC.Controllers.DepartmentController
A***.Benutzerverwaltung.API.Controllers.DepartmentController
So i renamed the first namespace into the second, i searched everywhere for the old namespace, but nothing was found. So, what could i do?
Thanks for help.
So, what could i do?
Go to the bin folder of your web application and delete the old assemblies. ASP.NET loads all assemblies that are present in the bin folder. So if you are saying that you renamed some class library project reference, the old assembly is still physically there.