Previous working asp.net webforms app now throws this error:
System.MissingMethodException: Method not found
The DoThis
method is on the same class and it should work.
I have a generic handler as such:
public class MyHandler: IHttpHandler
{
public void Processrequest(HttpContext context)
{
// throws error now System.MissingMethodException:
// Method not found.
this.DoThis();
}
public void DoThis(){ ... }
}
ΩmegaMan
29.1k10 gold badges99 silver badges121 bronze badges
asked Nov 9, 2011 at 0:09
user603007user603007
11.3k38 gold badges103 silver badges167 bronze badges
3
This is a problem which can occur when there is an old version of a DLL still lingering somewhere around. Make sure that the latest assemblies are deployed and no duplicated older assemblies are hiding in certain folders. Your best bet would be to delete every built item and rebuild/redeploy the entire solution.
Luke Girvin
13.2k9 gold badges63 silver badges84 bronze badges
answered Nov 9, 2011 at 2:10
13
⚠️ Wrong Nuget Package Version ⚠️
I had a unit test project which was pulling in our companies internal EF Nuget data access package and that code pulled in an external package whose version was way behind the current version.
The issue was that the Nuget settings for the top level package was set to the least version
; and the lower level/older version won, and that was used during the operations….
Hence it silently got the wrong version for a common assembly used by both the package and the app.
💡 Solution 💡
By Setting/updating the package in Nuget to use and [get] the latest, fixed the issue.
answered Mar 31, 2016 at 21:39
ΩmegaManΩmegaMan
29.1k10 gold badges99 silver badges121 bronze badges
3
I resolved this issue by installing the correct .NET Framework version on the server. The website was running under version 4.0 and the assembly it was calling to was compiled for 4.5. After installation of .NET Framework 4.5 and upgrading the website to 4.5, all works fine.
answered Jul 6, 2013 at 23:41
Ben GripkaBen Gripka
15.9k6 gold badges45 silver badges41 bronze badges
2
Restarting Visual Studio actually fixed it for me. I’m thinking it was caused by old assembly files still in use, and performing a «Clean Build» or restarting VS should fix it.
wonea
4,73317 gold badges85 silver badges139 bronze badges
answered Feb 12, 2015 at 3:26
JelaniJelani
7056 silver badges25 bronze badges
0
Check your References!
Be sure that you are consistently pointing to the same 3rd party libraries (don’t just trust versions, look at the path) across your solutions projects.
For example, If you use iTextSharp v.1.00.101 in one project and you NuGet or reference iTextSharp v1.00.102 somewhere else you will get these types of runtime errors that somehow trickle up into your code.
I changed my reference to iTextSharp in all 3 projects to point to the same DLL and everything worked.
answered Jan 24, 2017 at 9:19
JulsJuls
6236 silver badges15 bronze badges
2
also.. try to «clean» your projects or solution and rebuild again!
answered Nov 12, 2013 at 22:47
user384080user384080
4,57615 gold badges63 silver badges96 bronze badges
I had this happen to me with a file referenced in the same assembly, not a separate dll. Once I excluded the file from the project and then included it again, everything worked fine.
answered Aug 17, 2012 at 20:30
Josh NoeJosh Noe
2,6582 gold badges35 silver badges37 bronze badges
0
I just ran into this on a .NET MVC project. The root cause was conflicting versions of NuGet packages. I had a solution with several projects. Each of the projects had some NuGet packages. In one project I had a version of the Enterprise Library Semantic Logging package, and in two other projects (that reference the first) I had older versions of the same package. It all compiles without error, but it gave a mysterious «Method not found» error when I tried to use the package.
The fix was to remove the old NuGet packages from the two projects, so that it was only included in the one project that actually needed it. (Also I did a clean rebuild of the whole solution.)
answered May 1, 2014 at 22:35
Mark MeuerMark Meuer
7,1516 gold badges43 silver badges64 bronze badges
If developing with your own NuGet server, make sure the assembly versions are all the same:
[assembly: AssemblyVersion("0.2.6")]
[assembly: AssemblyFileVersion("0.2.6")]
[assembly: AssemblyInformationalVersion("0.2.6")]
answered Aug 25, 2013 at 23:32
sennettsennett
7,9849 gold badges45 silver badges69 bronze badges
2
Have you tried turning if off and on again? Jokes aside, restarting my computer was what actually did the trick for me and isn’t mentioned in any of the other answers.
answered Jan 22, 2014 at 9:44
Lee BaileyLee Bailey
3,5642 gold badges18 silver badges17 bronze badges
I’ve just had this issue and it turned out that it was because I was referencing a previous version of the DLL from my UI project. Therefore, when compiling it was happy. But when running it was using the previous version of the DLL.
Check references on all other projects before assuming you need to rebuild/clean/redeploy your solutions.
answered Apr 6, 2016 at 13:36
It’s also possible the problem is with a parameter or return type of the method that’s reported missing, and the «missing» method per se is fine.
That’s what was happening in my case, and the misleading message made it take much longer to figure out the issue. It turns out the assembly for a parameter’s type had an older version in the GAC, but the older version actually had a higher version number due to a change in version numbering schemes used. Removing that older/higher version from the GAC fixed the problem.
answered Sep 5, 2017 at 21:16
JimmyJimmy
414 bronze badges
In my case it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(take note of the missing «public» in front of the ctor)
which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can’t (of course!) find the constructor!
answered Oct 4, 2017 at 14:35
DaBeSoftDaBeSoft
491 silver badge5 bronze badges
2
Using Costura.Fody 1.6 & 2.0:
After wasting a bunch of time looking into this same kind of error with all other potential solutions not working, I found that an older version of the DLL I was embedding was in the same directory I was running my newly compiled .exe from. Apparently it looks for a local file in the same directory first, then looks inward to its embedded library. Deleting the old DLL worked.
To be clear, it wasn’t that my reference was pointing to an old DLL, it was that a copy of an old DLL was in the directory I was testing my application from on a separate system from that which it was compiled on.
answered Apr 20, 2018 at 16:15
grep65535grep65535
431 silver badge6 bronze badges
1
In my case, the MissingMethodException was for a method that was in the same file!
However, I had just added a NuGet package that uses .Net Standard2 to my 4.7.1-targeting project, which caused a version conflict for System.Net.Http (4.7.1: version 4.0.0.0, the NuGet package using .NET Standard 2 wants 4.2.0.0). This seem to be known issues that should be better in 4.7.2 (see note 2).
I had used a binding redirect like this in all other my projects, because there were exceptions as soon as it tried to load the 4.2.0.0 which I didn’t have:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
Except in this one project, where it seems it tries to load System.Net.Http only while calling a local function that uses a System.Net.Http.HttpResponseMessage as it’s parameter or return type (parameter during debugging, return type when I run the tests without the debugger, also a bit strange). And instead of showing a message that it could not load the 4.2.0.0 version of System.Net.Http, it returns this exception.
answered Oct 8, 2019 at 12:40
LegolasLegolas
8841 gold badge11 silver badges25 bronze badges
I had a similar scenario where I was getting this same exception being thrown. I had two projects in my web application solution, named, for sake of example, DAL and DAL.CustSpec. The DAL project had a method named Method1, but DAL.CustSpec did not. My main project had a reference to the DAL project and also a reference to another project named AnotherProj. My main project made a call to Method1. The AnotherProj project had a reference to the DAL.CustSpec project, and not the DAL project. The Build configuration had both the DAL and DAL.CustSpec projects configured to be built. After everything was built, my web application project had the AnotherProj and DAL assemblies in its Bin folder. However, when I ran the website, the Temporary ASP.NET folder for the website had the DAL.CustSpec assembly in its files and not the DAL assembly, for some reason. Of course, when I ran the part that called Method1, I received a «Method not found» error.
What I had to do to fix this error was to change the reference in the AnotherProj project from DAL.CustSpec to just DAL, deleted all the files in the Temporary ASP.NET Files folder, and then reran the website. After that, everything started working. I also made sure that the DAL.CustSpec project was not being built by unchecking it in the Build Configuration.
I thought I would share this in case it helps someone else in the future.
answered Mar 30, 2013 at 19:19
I came across the same situation in my ASP.NET website. I deleted the published files, restarted VS, cleaned and rebuild the project again. After the next publish, the error was gone…
answered Jul 8, 2015 at 9:54
IrshuIrshu
8,1788 gold badges53 silver badges64 bronze badges
I solved this problem by making a shelveset with my changes and running TFS Power Tools ‘scorch’ in my workspace (https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f). Then I unshelved the changes and recompiled the project.
This way you will cleanup any ‘hanging-parties’ that may be around in your workspace and will startup with a fresh one.
This requires, of course, that you are using TFS.
answered Sep 17, 2015 at 8:30
Must be a reference bug from Microsoft.
I cleaned, rebuild on all my libraries and still got the same problem and couldnt resolve this.
All i did was close the Visual Studio Application and opened it again. That did the trick.
Its very frustrating that such a simple issue can take that long to fix because you wouldnt think that it will be something like that.
answered Jan 29, 2019 at 18:14
In my case, my project was referencing Microsoft.Net.Compilers.2.10.0
. When I switched it to Microsoft.Net.Compilers.2.7.0
, the error went away. What a mysterious error with such a variety of causes.
answered Feb 7, 2019 at 18:00
jaycerjaycer
2,9312 gold badges26 silver badges36 bronze badges
In my case it was a folder with olders DLLs of the same name that those wich were referenced in my .csproj file although the path was explicitly given they were somehow included therefore the several versions of the same DLLs were in conflict.
answered Feb 19, 2019 at 14:21
This may have been mentioned already, but for me the problem was that the project was referencing 2 nuget packages, and each of those nuget packages referenced a different version of another nuget package.
So:
Project -> Nuget A -> Nuget X 1.1
Project -> Nuget B -> Nuget X 1.2
Both versions of Nuget X had the same extension method that was being called from Project.
When I updated both Nuget A & B to versions that referenced the same version of Nuget X, the error went away.
answered Dec 19, 2019 at 14:45
Shahin DohanShahin Dohan
5,9793 gold badges38 silver badges58 bronze badges
Possible case could be
Mismatched nuget assembles versions
Problem In Detail
We had more then one nuget packages being generated by a solution.
Class A in packageA 1.0
Class B in packageB 1.0
A is referring B
so when A and B both have update we have to update packageA and packageB, but issue was one of my team member did not update packageB
now PackageA 1.1 still has dependency on PackageB 1.0 But PackageB don’t have updated version of Class B
and hence it was not been able to find the method
Solution
Move both packages to +1 Version
in this case I moved
PackageA 1.1 -> PackageA 1.2
PackageB 1.0 -> PackageB 1.1
but to make matters more symmetrical to can move both to same Version
PackageA 1.1 -> PackageA 1.2
PackageB 1.0 -> PackageB 1.2
answered Apr 27, 2021 at 7:27
hananhanan
1,7381 gold badge14 silver badges19 bronze badges
This happened to me using MVC4, and I decided after reading this thread to rename the object that was throwing the error.
I did a clean and rebuild and noted that it was skipping two projects. When I rebuilt one of them, there was an error where I’d started a function and not finished it.
So VS was referencing a model that I had rewritten without asking me if I wanted to do that.
answered Jan 20, 2015 at 17:09
Just in case it helps anyone, although it’s an old issue, my problem was a bit odd.
I had this error while using Jenkins.
Eventually found out that the system date was manually set to a future date, which caused dll to be compiled with that future date. When the date was set back to normal, MSBuild interpreted that the file was newer and didn’t require recompile of the project.
answered Mar 16, 2015 at 19:04
I ran into this issue, and what it was for me was one project was using a List which was in Example.Sensors namespace and and another type implemented the ISensorInfo interface. Class Type1SensorInfo, but this class was one layer deeper in the namespace at Example.Sensors.Type1. When trying to deserialize Type1SensorInfo into the list, it threw the exception. When I added using Example.Sensors.Type1 into the ISensorInfo interface, no more exception!
namespace Example
{
public class ConfigFile
{
public ConfigFile()
{
Sensors = new List<ISensorInfo<Int32>>();
}
public List<ISensorInfo<Int32>> Sensors { get; set; }
}
}
}
**using Example.Sensors.Type1; // Added this to not throw the exception**
using System;
namespace Example.Sensors
{
public interface ISensorInfo<T>
{
String SensorName { get; }
}
}
using Example.Sensors;
namespace Example.Sensors.Type1
{
public class Type1SensorInfo<T> : ISensorInfo<T>
{
public Type1SensorInfo()
}
}
answered Aug 21, 2015 at 19:10
I’ve had the same thing happen when I had a number of MSBuild processes running in the background which had effectively crashed (they had references to old versions of code). I closed VS and killed all the MSBuild processes in process explorer and then recompiled.
answered Nov 26, 2015 at 15:43
bytedevbytedev
8,0943 gold badges48 silver badges56 bronze badges
I had a test project that references 2 other projects that each referenced different versions (in different locations) of the same dll. This confused the compiler.
answered Mar 1, 2017 at 23:25
nuandernuander
1,3191 gold badge19 silver badges32 bronze badges
In my case spotify.exe was using the same port which my web api project wanted to use on a development machine. The port number was 4381.
I quit Spotify and everything worked well again
answered Mar 17, 2017 at 16:48
Arda BasogluArda Basoglu
1,4001 gold badge11 silver badges6 bronze badges
Hi. I have read #6865, #6855, and https://blogs.msdn.microsoft.com/dotnet/2016/10/25/announcing-entity-framework-core-1-1-preview-1/ from the release.
I am trying to run Scaffold-DbContext "Server=(A);Database=B;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Verbose
I am getting the error Method Not Found as per the title (full error at the bottom). To try and resolve this I have
- updated the listed packages as detailed in the release blog.
- Kept using netcore 1.0.0
- run dotnet restore (many times)
- restarted VS and my machine (many times)
I have read that I may need to delete the Entity Framework directory under %USERPROFILE%/.nuget … but that seems a bit drastic.
Below is my project.json … I think I a missing something small and would appreciate any pointers to help through this. I did try rolling back to preview2-final on tools but it all seems to have gone a bit wrong.
`{
«dependencies»: {
«Microsoft.AspNetCore.Authentication»: «1.0.0»,
«Microsoft.AspNetCore.Authentication.Cookies»: «1.0.0»,
«Microsoft.AspNetCore.Authorization»: «1.0.0»,
«Microsoft.AspNetCore.Diagnostics»: «1.0.0»,
«Microsoft.AspNetCore.Identity»: «1.0.0»,
«Microsoft.AspNetCore.Mvc»: «1.0.1»,
«Microsoft.AspNetCore.Razor.Tools»: {
«version»: «1.0.0-preview2-final»,
«type»: «build»
},
«Microsoft.AspNetCore.Routing»: «1.0.1»,
«Microsoft.AspNetCore.Server.IISIntegration»: «1.0.0»,
«Microsoft.AspNetCore.Server.Kestrel»: «1.0.1»,
«Microsoft.AspNetCore.Session»: «1.0.0»,
«Microsoft.AspNetCore.StaticFiles»: «1.0.0»,
«Microsoft.EntityFrameworkCore.Design»: «1.0.1»,
«Microsoft.EntityFrameworkCore.SqlServer»: «1.1.0-preview1-final»,
«Microsoft.EntityFrameworkCore.SqlServer.Design»: «1.1.0-preview1-final»,
«Microsoft.EntityFrameworkCore.Tools.DotNet»: «1.0.0-preview3-final»,
«Microsoft.Extensions.Configuration.EnvironmentVariables»: «1.0.0»,
«Microsoft.Extensions.Configuration.Json»: «1.0.0»,
«Microsoft.Extensions.Logging»: «1.1.0-preview1-final»,
«Microsoft.Extensions.Logging.Console»: «1.0.0»,
«Microsoft.Extensions.Logging.Debug»: «1.0.0»,
«Microsoft.Extensions.Options.ConfigurationExtensions»: «1.0.0»,
«Microsoft.NETCore.App»: {
«version»: «1.0.1»,
«type»: «platform»
},
«Microsoft.VisualStudio.Web.BrowserLink.Loader»: «14.0.0»,
«Microsoft.VisualStudio.Web.CodeGeneration.Tools»: {
«version»: «1.0.0-preview2-final»,
«type»: «build»
},
«Microsoft.VisualStudio.Web.CodeGenerators.Mvc»: {
«version»: «1.0.0-preview2-final»,
«type»: «build»
}
},
«tools»: {
«BundlerMinifier.Core»: «2.0.238»,
«Microsoft.AspNetCore.Razor.Tools»: «1.0.0-preview2-final»,
«Microsoft.AspNetCore.Server.IISIntegration.Tools»: «1.0.0-preview2-final»,
«Microsoft.VisualStudio.Web.CodeGeneration.Tools»: {
«version»: «1.0.0-preview2-final»,
«imports»: [
«portable-net45+win8»
]
}
},
«frameworks»: {
«netcoreapp1.0»: {
«imports»: [
«dotnet5.6»,
«portable-net45+win8»
]
}
},
«buildOptions»: {
«emitEntryPoint»: true,
«preserveCompilationContext»: true
},
«runtimeOptions»: {
«configProperties»: {
«System.GC.Server»: true
}
},
«publishOptions»: {
«include»: [
«wwwroot»,
«**/*.cshtml»,
«appsettings.json»,
«web.config»
]
},
«scripts»: {
«prepublish»: [ «bower install», «dotnet bundle» ],
«postpublish»: [ «dotnet publish-iis —publish-folder %publish:OutputPath% —framework %publish:FullTargetFramework%» ]
}
}
`
and here is the full error message …
System.MissingMethodException: Method not found: 'System.String Microsoft.EntityFrameworkCore.Metadata.Internal.EntityTypeExtensions.DisplayName(Microsoft.EntityFrameworkCore.Metadata.IEntityType)'. at Microsoft.EntityFrameworkCore.Scaffolding.Internal.StringBuilderCodeWriter.WriteCodeAsync(ModelConfiguration modelConfiguration, String outputPath, String dbContextClassName, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineeringGenerator.GenerateAsync(ReverseEngineeringConfiguration configuration, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContextAsync(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable
1 schemas, IEnumerable1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.<ScaffoldContextImpl>d__22.MoveNext() at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable
1 source, Int32& length)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass4_0
1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)`
You might have had a situation where your code once worked fine in ASP.NET application but now throws the below error.
System.MissingMethodException: Method not found
I have noticed this more recently in the Outsystems Web Application.
One of the main reason for this error is that there is an old version of the DLL that might be referenced or still been used somewhere with your code.
To fix the Method not found error in C#, ensure that the latest assemblies are deployed and no duplicate or older assemblies are existing in any of the sub folders with-in your application.
When Deploying, also purge the entire folder before you deploy your .NET application.
- Remove From My Forums
-
Question
-
I have written an application in Visual Studio 2015 that uses C# 6.0 features and targets .NET 4.5.2. When I build it using Microsoft Build Tools 2015, a copy of the mscorlib.dll is included in my bin folder. This mscorlib.dll is the .NET 4.6 version of
the DLL and is not copied when I build the same project in Visual Studio 2015 (I am not sure if this piece of information is relevant).When I run the application on a system that has .NET 4.5.2 installed, I get the following error message:
Method not found: ‘System.String System.String.Format(System.IFormatProvider, System.String, System.Object, System.Object)’.The part of the code causing this error is a call to:
string.Format(CultureInfo.InvariantCulture, "{0}='{1}'", "key", "value")
Which resolves to:
public static string Format(IFormatProvider provider, string format, object arg0, object arg1)
Instead of:
public static string Format(IFormatProvider provider, string format, params object[] args)
Why is this happening? Here is what my DLL looks like when examined with the dotPeek decompiler:
Note that my DLL (Common) is targeting «.Net Framework 4.5.2». Also notice that the mscorlib it references is the .NET 4.5.2 one from:
C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5.2mscorlib.dllMy .csproj file has been setup to target .NET 4.5.2 properly! I am including the first few sections from it for reference:
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)$(MSBuildToolsVersion)Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)$(MSBuildToolsVersion)Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{4D75A799-231B-4057-B373-8C9EE73EC786}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Common</RootNamespace> <AssemblyName>Common</AssemblyName> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment>
...
I understand that, since I am using C# 6.0, I can use the new string interpolation syntax to avoid this problem. I am still curious, however, as to why it occurs and how it can be resolved without removing string.Format.
-
Edited by
Wednesday, November 25, 2015 12:14 PM
-
Edited by
Answers
-
Read the «Overload Resolution» of
this for the resolving order when other overloading function and function with optional parameter coexist.-
Marked as answer by
Philip Atz
Saturday, November 28, 2015 10:57 AM
-
Marked as answer by
-
The choice of function to use is determined at compile time. Since CSC defaults to include MSCORLIB itself, maybe that’s why it sees the function in the 4.6 version and think it should choose that run.
Maybe you should try the approach
here, to instruct it not to link the standard libraries automatically, and then explicitly add reference to the version of mscorlib you’ll be targeting at.See if this can resolve your problem.
-
Marked as answer by
Philip Atz
Saturday, November 28, 2015 10:56 AM
-
Marked as answer by
-
Yes, you are right in that the resolution into «object
arg0,
object arg1»
is occurring for the same reason that causes the 4.6 version of `mscorlib.dll` to be included in the build’s bin folder. The link you sent about getting rid of an MSCORLIB warning did not help me, but I now know what the problem was. Apparently, Microsoft
Build Tools 2015 builds with .NET 4.6 in mind, even if your project targets 4.5.2, unless you have the 4.5.2 Targeting Pack installed (which I didn’t). After installing the Targeting Pack, I can see that the bin folder produced by the Build Tools no longer
includes `mscorlib.dll`.I am undecided on whether this constitutes a bug for Build Tools 2015. I believe the Build Tools should produce an error, or at least a warning, saying that «You are trying to build an assembly that targets .NET 4.5.2 without having the 4.5.2 Targeting
Pack installed». This would make more sense than the Build Tools silently trying to compile the assembly with the .NET 4.6 resolution information they have available, bundling in the 4.6 `mscorlib.dll` in the process.Another thing that is highlighted by this are, I guess, the effects of Microsoft’s decision to add this new overload to .NET 4.6:
public static string Format(IFormatProvider provider, string format, object arg0, object arg1)
I believe it was a breaking change, only in subtle ways, and a bad one because of that.
-
Marked as answer by
Philip Atz
Saturday, November 28, 2015 10:57 AM
-
Marked as answer by
-
Thank you cheong00, that is an interesting read. I have tried the following code in LINQPad, which does indeed prove that «params object[] args»
is assigned lower resolution priority:void Main() { Test(CultureInfo.InvariantCulture, "{0}='{1}'", "key", "value"); Test(CultureInfo.InvariantCulture, "{0}='{1}'", args: new[] { "key", "value" }); } private static void Test(IFormatProvider provider, string format, object arg0, object arg1) { "object arg0, object arg1".Dump(); } private static void Test(IFormatProvider provider, string format, params object[] args) { "params object[] args".Dump(); }
The question still remains however: Why is «object
arg0,
object arg1»
even considered as an option for resolution of string.Format() when I am targeting .NET 4.5.2?-
Edited by
Philip Atz
Friday, November 27, 2015 11:37 AM -
Marked as answer by
Philip Atz
Saturday, November 28, 2015 10:57 AM
-
Edited by
26 ответов
Это проблема, которая может возникнуть, когда есть старая версия DLL, которая все еще задерживается где-то вокруг. Убедитесь, что последние сборки развернуты, а дублированные старые сборки не скрываются в определенных папках. Лучше всего было бы удалить каждый встроенный элемент и перестроить/переустановить все решение.
Polity
09 нояб. 2011, в 03:59
Поделиться
Я решил эту проблему, установив на сервере правильную версию .NET Framework. Веб-сайт работал под версией 4.0, а сборка, которую он вызывал, была скомпилирована для версии 4.5. После установки .NET Framework 4.5 и обновления сайта до версии 4.5 все работает нормально.
Ben Gripka
07 июль 2013, в 00:43
Поделиться
Перезапуск Visual Studio фактически исправил это для меня. Я думаю, что это было вызвано старыми файлами сборки, которые все еще используются, и выполнение «Чистой сборки» или перезапуск VS должно исправить это.
Jelani
12 фев. 2015, в 03:38
Поделиться
Неправильная версия пакета Nuget
У меня был проект модульного тестирования, который включал пакет доступа к данным EF Nuget наших компаний, и эта версия сильно отставала от текущей версии.
Для параметров Nuget для упомянутого пакета была установлена least version
для тех других пакетов, которые были зависимыми от второго уровня.
Следовательно, он молча получил неправильную версию для соответствующей сборки.
Решение
Установив/обновив пакет в Nuget, чтобы [получить] последний исправил проблему.
ΩmegaMan
31 март 2016, в 22:56
Поделиться
Я просто столкнулся с этим в проекте .NET MVC. Коренной причиной были конфликтующие версии пакетов NuGet. У меня было решение с несколькими проектами. В каждом из проектов были некоторые пакеты NuGet. В одном проекте у меня была версия пакета Semantic Logging Enterprise Library, а в двух других проектах (эта ссылка была первой) у меня были более старые версии одного и того же пакета. Все они компилируются без ошибок, но при попытке использовать пакет он дал загадочную ошибку «Метод не найден».
Исправлено удаление старых пакетов NuGet из двух проектов, так что он был включен только в один проект, который действительно нуждался в нем. (Также я сделал чистую перестройку всего решения.)
Mark Meuer
01 май 2014, в 23:46
Поделиться
У меня это случилось со мной с файлом, указанным в той же сборке, а не с отдельной dll. Как только я исключил файл из проекта, а затем включил его снова, все работало нормально.
Josh Noe
17 авг. 2012, в 20:33
Поделиться
Если вы разрабатываете свой собственный сервер NuGet, убедитесь, что все версии сборки одинаковы:
[assembly: AssemblyVersion("0.2.6")]
[assembly: AssemblyFileVersion("0.2.6")]
[assembly: AssemblyInformationalVersion("0.2.6")]
sennett
26 авг. 2013, в 00:16
Поделиться
Проверьте свои ссылки!
Убедитесь, что вы последовательно указываете на те же сторонние библиотеки (не просто доверяйте версиям, смотрите путь) в проектах решений.
Например, если вы используете iTextSharp v.1.00.101 в одном проекте, а вы NuGet или ссылаетесь на iTextSharp v1.00.102, то в другом месте вы получите эти типы ошибок времени выполнения, которые каким-то образом стекаются в ваш код.
Я изменил свою ссылку на iTextSharp во всех трех проектах, чтобы указать на одну и ту же DLL, и все сработало.
Juls
24 янв. 2017, в 09:24
Поделиться
также попробуйте «очистить» ваши проекты или решение и снова восстановить!
user384080
12 нояб. 2013, в 23:09
Поделиться
У меня была эта проблема, и оказалось, что это связано с тем, что я ссылался на предыдущую версию DLL из моего проекта пользовательского интерфейса. Поэтому при компиляции он был счастлив. Но при запуске он использовал предыдущую версию DLL.
Проверяйте ссылки на все другие проекты, прежде чем предполагать, что вам нужно перестроить/очистить/перераспределить ваши решения.
Jamie Lupton
06 апр. 2016, в 14:25
Поделиться
Использование Costura.Fody 1.6 и 2.0:
Потратив кучу времени на поиски такой же ошибки, когда все остальные потенциальные решения не работали, я обнаружил, что старая версия DLL, которую я встраивал, была в той же директории, из которой я запускал только что скомпилированный .exe. Очевидно, он сначала ищет локальный файл в том же каталоге, а затем смотрит внутрь своей встроенной библиотеки. Удаление старой DLL сработало.
Чтобы быть ясным, дело не в том, что моя ссылка указывала на старую DLL, а в том, что копия старой DLL была в каталоге, из которого я тестировал свое приложение в отдельной системе от той, на которой оно было скомпилировано.
grep 65535
20 апр. 2018, в 17:27
Поделиться
В моем случае это была проблема с копией/вставкой. Я как-то закончил конструктор PRIVATE для моего профиля отображения:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(обратите внимание на отсутствующую «общественность» перед ctor)
который скомпилирован отлично, но когда AutoMapper пытается создать экземпляр профиля, он не может (конечно!) найти конструктор!
DaBeSoft
04 окт. 2017, в 15:04
Поделиться
Также возможно, что проблема связана с параметром или возвращаемым типом метода, который сообщил об отсутствии, и «отсутствующий» метод сам по себе является прекрасным.
То, что происходило в моем случае, и вводящее в заблуждение сообщение заставило его заняться гораздо дольше, чтобы выяснить проблему. Оказывается, сборка для типа параметра имела более старую версию в GAC, но более старая версия имела более высокий номер версии из-за изменения используемых схем нумерации версий. Удаление этой старой/более высокой версии из GAC устранило проблему.
Jimmy
05 сен. 2017, в 21:58
Поделиться
Я решил эту проблему, сделав полки с моими изменениями и запустив TFS Power Tools ‘scorch’ в моей рабочей области (https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f). Затем я внесла изменения и перекомпилировал проект.
Таким образом, вы будете очищать любые «висячие партии», которые могут быть в вашем рабочем пространстве, и будут запускаться с новой.
Это требует, конечно, использования TFS.
fbastian
17 сен. 2015, в 09:45
Поделиться
Я столкнулся с такой же ситуацией на своем веб-сайте ASP.NET. Я удалил опубликованные файлы, перезапустил VS, снова очистил и перестроил проект. После следующего опубликования ошибка исчезла…
Irshu
08 июль 2015, в 10:42
Поделиться
Вы пытались поворачиваться, если снова и снова? Шутки в сторону, перезагрузка моего компьютера была тем, что на самом деле помогло и не упоминается ни в одном из других ответов.
Lee Bailey
22 янв. 2014, в 10:49
Поделиться
У меня был похожий сценарий, когда я получал такое же исключение. У меня было два проекта в моем решении для веб-приложений, названное, например, для DAL и DAL.CustSpec. Проект DAL имел метод Method1, но DAL.CustSpec этого не делал. В моем основном проекте была ссылка на проект DAL, а также ссылка на другой проект под названием AnotherProj. Мой главный проект сделал вызов Method1. Проект AnotherProj имел ссылку на проект DAL.CustSpec, а не на проект DAL. В конфигурации Build были сконфигурированы как проекты DAL, так и DAL.CustSpec. После того, как все было построено, в моем проекте веб-приложения были сборки AnotherProj и DAL в папке Bin. Однако, когда я запускал веб-сайт, временная папка ASP.NET для веб-сайта по какой-то причине имела сборку DAL.CustSpec в своих файлах, а не в сборке DAL. Конечно, когда я запускал часть, которая называлась Method1, я получил ошибку «Метод не найден».
Что мне нужно было сделать, чтобы исправить эту ошибку, было изменение ссылки в проекте AnotherProj из DAL.CustSpec только на DAL, удаление всех файлов в папке Временные файлы ASP.NET и повторный веб-сайт. После этого все приступило к работе. Я также убедился, что проект DAL.CustSpec не был создан, сняв флажок в конфигурации сборки.
Я думал, что поделюсь этим, если это поможет кому-то еще в будущем.
Ron Kanagy
30 март 2013, в 20:30
Поделиться
Должно быть ссылочной ошибкой от Microsoft.
Я почистил, пересобрал все мои библиотеки и все еще получил ту же проблему и не мог решить эту проблему.
Я только закрыл приложение Visual Studio и снова открыл его. Это добилось цели.
Очень обидно, что такая простая проблема может так долго решаться, потому что вы не думаете, что это будет что-то подобное.
JayJay Barnard
29 янв. 2019, в 20:07
Поделиться
В моем случае не было никакого изменения кода вообще, и внезапно один из серверов начал получать это и только это исключение (все серверы имеют одинаковый код, но только у одного начались проблемы):
System.MissingMethodException: Method not found: '?'.
стек:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
at myAccountSearch.AccountSearchClient.searchtPhone(String ID, String HashID, searchtPhone Phone1)
at WS.MyValidation(String AccountNumber, String PhoneNumber)
Я считаю, что проблема была повреждена AppPool — мы автоматизировали утилизацию AppPool каждый день в 3 часа ночи, и проблема началась в 3 часа ночи, а затем закончилась сама по себе в 3 часа ночи на следующий день.
George
29 май 2018, в 22:40
Поделиться
У меня была эта проблема, когда метод требовал параметр, который я не указывал
R2D2
21 май 2018, в 10:17
Поделиться
В моем случае spotify.exe использовал тот же порт, который мой веб-проект api хотел использовать на машине разработки. Номер порта был 4381.
Я ухожу из Spotify, и все снова работает хорошо:)
Arda Basoglu
17 март 2017, в 18:13
Поделиться
У меня был тестовый проект, который ссылается на 2 других проекта, каждый из которых ссылается на разные версии (в разных местах) одной и той же DLL. Это путало компилятор.
nuander
01 март 2017, в 23:47
Поделиться
У меня было то же самое, когда у меня было несколько процессов MSBuild, работающих в фоновом режиме, которые эффективно разбились (у них были ссылки на старые версии кода). Я закрыл VS и убил все процессы MSBuild в проводнике процессов, а затем перекомпилировал.
bytedev
26 нояб. 2015, в 16:51
Поделиться
Я столкнулся с этой проблемой, и то, что для меня было одним проектом, было использование списка, который был в примере. Пространство имен сенсоров, а другой тип — интерфейс ISensorInfo. Класс Type1SensorInfo, но этот класс был одним слоем глубже в пространстве имен в примере. Sensors.Type1. При попытке десериализовать Type1SensorInfo в список, это исключило исключение. Когда я добавил использование примера .Sensors.Type1 в интерфейс ISensorInfo, больше никаких исключений!
namespace Example
{
public class ConfigFile
{
public ConfigFile()
{
Sensors = new List<ISensorInfo<Int32>>();
}
public List<ISensorInfo<Int32>> Sensors { get; set; }
}
}
}
**using Example.Sensors.Type1; // Added this to not throw the exception**
using System;
namespace Example.Sensors
{
public interface ISensorInfo<T>
{
String SensorName { get; }
}
}
using Example.Sensors;
namespace Example.Sensors.Type1
{
public class Type1SensorInfo<T> : ISensorInfo<T>
{
public Type1SensorInfo()
}
}
Steven Koxlien
21 авг. 2015, в 20:31
Поделиться
На всякий случай это помогает любому, хотя это старая проблема, моя проблема была немного странной.
У меня была эта ошибка при использовании Jenkins.
В конце концов выяснилось, что системная дата была вручную установлена на будущую дату, что вызвало слияние dll с этой будущей датой. Когда дата была возвращена в нормальное состояние, MSBuild интерпретировал, что файл был более новым и не требовал перекомпиляции проекта.
Renato Chencinski
16 март 2015, в 20:40
Поделиться
Это случилось со мной с помощью MVC4, и я решил после прочтения этого потока переименовать объект, который выдавал ошибку.
Я сделал чистую и восстановил и отметил, что он пропускает два проекта. Когда я перестроил один из них, произошла ошибка, когда я запустил функцию и не закончил ее.
Итак, VS ссылался на модель, которую я переписал, не спрашивая меня, хочу ли я это сделать.
TheWizardOfTN
20 янв. 2015, в 18:53
Поделиться
Ещё вопросы
- 0Форма регистрации дня рождения Trouple
- 0нанесение логотипа на вкладку Jquery
- 0Временно отсоединить перетаскиваемое колесо мыши от карты масштабирования / панорамирования?
- 0Активировать текстовое поле, когда пользователь выбирает значение в выпадающем списке
- 1DropDownList не заполнен из базы данных SQL
- 0Скачать файл с URL как вложение
- 0Почему HTML 5 Canvas не рисует содержимое изображения?
- 1Как сохранить лучшие веса части энкодера только во время обучения авто-энкодеру ??
- 1c # назначить кнопку пользовательское расположение на FlowLayoutPanel
- 1Как передать переменные из одного JSP в другой, не делая их переменными сеанса?
- 0Захватить jQuery Маскированный ввод Изменение ввода
- 1Как преобразовать файл с разделителем канала с несколькими тысячами записей в XML в муле
- 0когда запускается SDL_MOUSEBUTTONUP?
- 0Как создать функцию обновления на nodejs / mongodb?
- 1Заполните все значения в группе первым ненулевым значением в этой группе
- 0Возврат и передача массива для работы в C ++
- 0Я пытаюсь заполнить поле со списком в front-end значением поля из базы данных
- 1Разница между Groovy 1.6 и 1.8
- 0Кнопка подписки YouTube (вставка) не работает
- 1заменить все выбранные значения как NaN в пандах
- 1Читать значения из узлов XML?
- 0невозможно загрузить динамическую библиотеку
- 1Нумерация страниц с помощью startAt () при заказе ребенком
- 1Получение FileNotFoundException при попытке поделиться MP3 через неявное намерение с использованием FileProvider
- 0Btn-group, накладывающаяся на изменение размера окна (меньше)
- 0Оператор SELECT, вызванный из асинктической задачи HTTP post, терпит неудачу ТОЛЬКО на устройстве galaxy s4
- 1Приложение MVC 4.0 .NET и значения, возвращаемые из базы данных после развертывания в IIS
- 1Открытие и закрытие компактного фреймворка мультиформного приложения
- 1некоторые настройки в VS Code
- 1чтение структуры каталогов и преобразование ее в объект JSON в Java
- 0Размер массива ограничен в PHP scandir ()
- 0граница не расширяется — css
- 0Javascript конвертировать [url =] в HTML ссылку
- 1FusedLocationProvider иногда дает неверное местоположение
- 0c # genereic sql context patameter
- 0Как удалить просроченные маркеры доступа из БД
- 1Bs4 кодировать Проблема — Python
- 0сделать фоновое изображение div
- 1Найти совпадающее содержимое и длину массива в одном внутреннем свойстве
- 0Как Yii SQL Нравится
- 0std :: bad_cast при использовании std :: basic_istringstream <unsigned short>
- 1Jade / мопс выберите форму Javascript Onchange событие
- 1dc.js Вид по умолчанию для таблицы строк отсортирован и не переупорядочивается при нажатии
- 0HTML5 и PHP: Воспроизведение видеофайла в формате base64
- 0почему оповещение не срабатывает с помощью угловых JS в контроллере
- 0Диалоговое окно jQuery UI, не закрывать и не выполнять
- 1Чтение XML-файла из определенных тегов
- 1bs4 не может вызвать findchildren из-за NoneType
- 0Angular UI Router загружен, но не передает параметры
- 1Шкала оценок в Java