- Create a new ASP.NET MVC Web
Application - Create an ASP.NET App_Code
Folder -
Inside the new
folder, create a class with an
Extension Method. For example:static public class BugMVCExtension { public static int ToInt(this string str) { return Convert.ToInt32(str); } } -
Choose a View and try to use this new Extension Method
You will get this Exception:
CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'
Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?
MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.
Update:
Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.
answered Aug 15, 2009 at 19:32
![]()
Mehrdad AfshariMehrdad Afshari
413k91 gold badges851 silver badges789 bronze badges
8
Do not use the app_code folder.
Use any other folder name. IE. appCode or ApplicationsCode.
The name in the folder implies some compilation at runtime that leads to have duplicated code.
1
I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.
I solved by placing in the file of extension of the full namespace of the folder.
namespace Helpers
{
namespace xxx.yyy.zzz.Helpers
{
This is the craziest what I’ve seen since a Fody plugin ruined my assembly by emitting invalid code and control flow varied random at runtime… No Fody this time.
Facts:
- The whole story is within one project.
- The GetMessage extension method is there since weeks…
- The issue is started since 2 hours, and I can not figure out what it is.
- There is only one GetMessage extension method.
-
The error message (see the pic) lists two identical method specification
Error CS0121 The call is ambiguous between the following methods or properties: 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' and 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' ComiCalc.Data D:2014Develop.vsonlineComiCalcsrcComiCalc.DataServicesUserService.cs 61
-
If I change both the call, both the method definition (only 2 edits in 2 places) to GetMessage2, then I got exactly the same error message just referring to the GetMessage2.
- Using VS 2015
Any ideas?

and here is the single one method:
namespace ComiCalc.Data
{
using System;
using System.Data.Entity.Validation;
using PluralTouch.DataAccess;
// TODO: Move to PluralTouch
public static class ExceptionExtensions
{
public static string GetMessage2(this Exception exception)
{
var message = exception.Message;
if (exception is DbEntityValidationException)
{
message = ((DbEntityValidationException) exception).DbEntityValidationResultToString();
}
return message;
}
}
}

asked Jul 30, 2015 at 16:24
![]()
g.pickardoug.pickardou
31.7k35 gold badges122 silver badges261 bronze badges
6
Make sure you don’t reference the output binary in your project references (i.e., the project references itself). This has happened to me in the past with Resharper (the addition of the output binary to the project references), so the extension method is both in the source and in the binary reference.
answered Jul 30, 2015 at 16:29
JclJcl
27.5k5 gold badges60 silver badges90 bronze badges
2
Delete bin folder > open project > build solution.
answered Apr 15, 2018 at 13:08
![]()
serdarserdar
4541 gold badge8 silver badges26 bronze badges
Got the same error because my project referenced to a dll, and at the same time had a transitive dependency to the same dll but at different file path.
Spotted it using extra logging during the build (Tools -> Options -> Build and Run ->output verbosity to Detailed or Diagnostic) by searching for dependency dll name: in Task «Csc» there were two occurrences of /reference with the dll
Fix was to point references to the same dll path
answered Feb 27, 2019 at 13:00
RenatRenat
7,5702 gold badges20 silver badges34 bronze badges
In my case, Resharper had created a new file named Annotations1.cs file. I just deleted it and the problem solved. Maybe you need delete debug / release / obj and clean / rebuild solution.

answered Feb 24, 2021 at 19:52
![]()
AyubAyub
2,33527 silver badges29 bronze badges
I created a new project and moved all files except ‘bin’, ‘references’, ‘obj’ and boom. It works like charm..
answered Apr 29, 2017 at 15:08
![]()
ErdoganErdogan
95212 silver badges25 bronze badges
I had two exact classes created by a DB tool, because was executed 2 times with different parameters. I search by the class name and remove the newer, after that everything goes OK.
answered Oct 6, 2020 at 5:07
In my case I had the «publish» folder within my project folder. Removing the «publish» folder solved it for me.
answered Oct 21, 2020 at 8:51
![]()
In my case, I hit the same problem [impossible resolution conflicts between a single method and itself] because I used C# 8.0 and its shiny new features to build three projects that depend upon each other, transitively, like this:
- Project C depends on project B.
- Project B depends on project A.
- Project C calls APIs from types in project B that inherit types from project A. Some of those APIs have nullable reference type parameters.
Also, I had nullability checking enabled only for project A, and completely disabled for projects B and C.
The fix for me was to enable nullable annotations in project B (I did this without also enabling warnings).
I speculate that this fixes the problem by ensuring there weren’t two completely different compiler modes (nullable annotated on/off) reprocessing the same interface definition, while building two projects (A and B), and then up putting conflicting nullability annotations on their respective outputs.
answered Sep 2, 2021 at 22:48
Tim Lovell-SmithTim Lovell-Smith
15k14 gold badges74 silver badges93 bronze badges
I had the same issue while migrating from .NET3.1 to .NET6.0. I got my issue fixed by updating the reference package «System.Interactive» to the latest version (6.0.1 in my case) in csproj file.
answered Feb 2 at 6:23
In my case I just have add «path» to the code!!! hope that helps error CS0121
answered Feb 27 at 20:32
- Create a new ASP.NET MVC Web
Application - Create an ASP.NET App_Code
Folder -
Inside the new
folder, create a class with an
Extension Method. For example:static public class BugMVCExtension { public static int ToInt(this string str) { return Convert.ToInt32(str); } } -
Choose a View and try to use this new Extension Method
You will get this Exception:
CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'
Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?
MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.
Update:
Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.
answered Aug 15, 2009 at 19:32
![]()
8
Do not use the app_code folder.
Use any other folder name. IE. appCode or ApplicationsCode.
The name in the folder implies some compilation at runtime that leads to have duplicated code.
1
I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.
I solved by placing in the file of extension of the full namespace of the folder.
namespace Helpers
{
namespace xxx.yyy.zzz.Helpers
{
- Create a new ASP.NET MVC Web
Application - Create an ASP.NET App_Code
Folder -
Inside the new
folder, create a class with an
Extension Method. For example:static public class BugMVCExtension { public static int ToInt(this string str) { return Convert.ToInt32(str); } } -
Choose a View and try to use this new Extension Method
You will get this Exception:
CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'
Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?
MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.
Update:
Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.
answered Aug 15, 2009 at 19:32
![]()
8
Do not use the app_code folder.
Use any other folder name. IE. appCode or ApplicationsCode.
The name in the folder implies some compilation at runtime that leads to have duplicated code.
1
I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.
I solved by placing in the file of extension of the full namespace of the folder.
namespace Helpers
{
namespace xxx.yyy.zzz.Helpers
{
This is the craziest what I’ve seen since a Fody plugin ruined my assembly by emitting invalid code and control flow varied random at runtime… No Fody this time.
Facts:
- The whole story is within one project.
- The GetMessage extension method is there since weeks…
- The issue is started since 2 hours, and I can not figure out what it is.
- There is only one GetMessage extension method.
-
The error message (see the pic) lists two identical method specification
Error CS0121 The call is ambiguous between the following methods or properties: 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' and 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' ComiCalc.Data D:2014Develop.vsonlineComiCalcsrcComiCalc.DataServicesUserService.cs 61
-
If I change both the call, both the method definition (only 2 edits in 2 places) to GetMessage2, then I got exactly the same error message just referring to the GetMessage2.
- Using VS 2015
Any ideas?

and here is the single one method:
namespace ComiCalc.Data
{
using System;
using System.Data.Entity.Validation;
using PluralTouch.DataAccess;
// TODO: Move to PluralTouch
public static class ExceptionExtensions
{
public static string GetMessage2(this Exception exception)
{
var message = exception.Message;
if (exception is DbEntityValidationException)
{
message = ((DbEntityValidationException) exception).DbEntityValidationResultToString();
}
return message;
}
}
}

asked Jul 30, 2015 at 16:24
![]()
g.pickardoug.pickardou
30.5k35 gold badges114 silver badges248 bronze badges
6
Make sure you don’t reference the output binary in your project references (i.e., the project references itself). This has happened to me in the past with Resharper (the addition of the output binary to the project references), so the extension method is both in the source and in the binary reference.
answered Jul 30, 2015 at 16:29
JclJcl
27.2k5 gold badges60 silver badges87 bronze badges
2
Delete bin folder > open project > build solution.
answered Apr 15, 2018 at 13:08
![]()
serdarserdar
4451 gold badge8 silver badges26 bronze badges
Got the same error because my project referenced to a dll, and at the same time had a transitive dependency to the same dll but at different file path.
Spotted it using extra logging during the build (Tools -> Options -> Build and Run ->output verbosity to Detailed or Diagnostic) by searching for dependency dll name: in Task «Csc» there were two occurrences of /reference with the dll
Fix was to point references to the same dll path
answered Feb 27, 2019 at 13:00
RenatRenat
7,2202 gold badges20 silver badges33 bronze badges
In my case, Resharper had created a new file named Annotations1.cs file. I just deleted it and the problem solved. Maybe you need delete debug / release / obj and clean / rebuild solution.

answered Feb 24, 2021 at 19:52
![]()
AyubAyub
2,24526 silver badges29 bronze badges
I created a new project and moved all files except ‘bin’, ‘references’, ‘obj’ and boom. It works like charm..
answered Apr 29, 2017 at 15:08
![]()
ErdoganErdogan
95212 silver badges25 bronze badges
I had two exact classes created by a DB tool, because was executed 2 times with different parameters. I search by the class name and remove the newer, after that everything goes OK.
answered Oct 6, 2020 at 5:07
In my case I had the «publish» folder within my project folder. Removing the «publish» folder solved it for me.
answered Oct 21, 2020 at 8:51
![]()
In my case, I hit the same problem [impossible resolution conflicts between a single method and itself] because I used C# 8.0 and its shiny new features to build three projects that depend upon each other, transitively, like this:
- Project C depends on project B.
- Project B depends on project A.
- Project C calls APIs from types in project B that inherit types from project A. Some of those APIs have nullable reference type parameters.
Also, I had nullability checking enabled only for project A, and completely disabled for projects B and C.
The fix for me was to enable nullable annotations in project B (I did this without also enabling warnings).
I speculate that this fixes the problem by ensuring there weren’t two completely different compiler modes (nullable annotated on/off) reprocessing the same interface definition, while building two projects (A and B), and then up putting conflicting nullability annotations on their respective outputs.
answered Sep 2, 2021 at 22:48
Tim Lovell-SmithTim Lovell-Smith
14.7k14 gold badges73 silver badges92 bronze badges
C# Compiler Error
CS0121 – The call is ambiguous between the following methods or properties: ‘method1’ and ‘method2′
Reason for the Error
You will receive this error when you usually call one of the overloaded method and the C# compiler is not able to call it because of the conflict with the parameters caused by implicit conversion.
For example, let’s have a look at the below C# code snippet.
namespace DeveloperPublishNamespace
{
public class DeveloperPublish
{
public static void Method1(int input1,double input2)
{
}
public static void Method1(double input1,int input2)
{
}
public static void Main()
{
Method1(5,5);
}
}
}
This contains 2 overloaded functions with different parameter type. When this function is called with the parameter 5,5, it results with the below error.
Error CS0121 The call is ambiguous between the following methods or properties: ‘DeveloperPublish.Method1(int, double)’ and ‘DeveloperPublish.Method1(double, int)’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

C# compiler was not able to identify which overloaded method to call because of the values that is passed which results in the implicit conversion.
Solution
There are plenty of ways in which you can avoid this error. You can either specify the parameter type with the explicit conversion so that the implicit conversion doesn’t take place or possibly use a named arguments.
Ошибка при компиляции — Неоднозначный вызов следующих методов или свойств Task.Run
Ошибка при компиляции — Неоднозначный вызов следующих методов или свойств Task.Run
- Статус темы:
-
Закрыта.
-
Добрый день! Скачал с гитхаба последнюю версию проекта. При компиляции проекта выдаются ошибки:
Ошибка CS0121 Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)» OsEngine e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs 196 Активный
Серьезность Код Описание Проект Файл Строка Состояние подавления
Ошибка CS0121 Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)» OsEngine e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs 325 АктивныйСкачать error.png 60 Кб
arkadiy_vl
-
Цитата: arkadiy_vl
Добрый день! Скачал с гитхаба последнюю версию проекта. При компиляции проекта выдаются ошибки:
Ошибка CS0121 Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)» OsEngine e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs 196 Активный
Серьезность Код Описание Проект Файл Строка Состояние подавления
Ошибка CS0121 Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)» OsEngine e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs 325 Активныйзакомментируйте пока. Пройдёт. Поправим
Алексей Ван
-
фикс на гитХабе.
Только вот у меня эта ошибка не всплывала. Синтаксис поменял. Отпишитесь, отпустило или нет.
Алексей Ван
-
Цитата: Алексей Ван
Только вот у меня эта ошибка не всплывала. Синтаксис поменял. Отпишитесь, отпустило или нет.Добрый день, Алексей! Скачал последнюю версию с гитхаба. Проект скомпилировался без ошибок. Проблема с неоднозначным вызовом методов ушла. Спасибо!
arkadiy_vl
- Статус темы:
-
Закрыта..
Проекты MVC, созданные в Visual Studio, используют модель проекта веб-приложения по умолчанию. App_Code в основном используется моделью веб-сайта. Я предлагаю прочитать о различиях между ними (другой вопрос охватывает этот вопрос, а также широко распространяется на MSDN). Если вы добавляете исходный файл в App_Code в проект веб-приложения, Visual Studio будет компилировать его в DLL (так как он включен в проект) и помещает его в /bin. Во время выполнения компилятор ASP.NET видит App_Code и пытается скомпилировать источник в другой сборке. Как следствие, два разных класса с одинаковыми именами будут существовать в двух разных сборках, и когда парсер ASP.NET попытается скомпилировать файл .aspx, он не сможет выбрать его.
Обновление:
Являются ли эти два (метод расширения и класс, который вы создаете) в одном файле .cs? В противном случае, возможно, создаваемый вами класс находится в исходном файле с Строить действие (щелкните правой кнопкой мыши по файлу, щелкните свойства), установленным в Контент, который сообщает Visual Studio пропустить он в процессе сборки (в этом случае вы не сможете ссылаться на него в других файлах .cs, которые находятся за пределами App_Code, но вы сможете использовать его в представлении, поскольку он только оживет во время выполнения.) Если действие сборки Компилировать, вы получите сообщение об ошибке. Эта проблема определенно не специфична для методов расширения. Visual Studio кажется достаточно умным, чтобы установить его в Content по умолчанию для исходных файлов, добавленных в App_Code.
#c# #implicit-conversion #ambiguous-call
Вопрос:
У меня есть несколько классов C#, MyChar, Myint, myDouble, которые переносят символы char, int и double. У каждого есть неявный оператор преобразования из обернутого типа в определенный пользователем. У меня также есть набор перегруженных функций, toString(MyChar), toString(myInt), toString(myDouble).
Я хочу вызвать toString(MyChar), передав буквальное значение символа, например «A». Но компиляция завершается неудачно с CS0121, «Вызов неоднозначен между следующими методами или свойствами:» toString(MyChar)» и «toString(myInt)»». И у меня возникает аналогичная проблема, если я передаю значение int.
public class MyChar
{
private MyChar(char val) => Value = val;
public static implicit operator MyChar(char val) => new MyChar(val);
public char Value { get; }
}
public class MyInt
{
private MyInt(int val) => Value = val;
public static implicit operator MyInt(int val) => new MyInt(val);
public int Value { get; }
}
public class MyDouble
{
private MyDouble(double val) => Value = val;
public static implicit operator MyDouble(double val) => new MyDouble(val);
public double Value { get; }
}
public class ConversionTests
{
public void DoIt()
{
Console.WriteLine(ToString('A')); // CS0121
Console.WriteLine(ToString(1)); // CS0121
}
private static string ToString(MyChar c) => $"{c.Value}";
private static string ToString(MyInt i) => $"{i.Value}";
private static string ToString(MyDouble d) => $"{d.Value}";
}
Я обнаружил, что могу заставить компилятор правильно принимать значение int, добавив неявное преобразование из myInt в myDouble
public class MyDouble
{
private MyDouble(double val) => Value = val;
public static implicit operator MyDouble(double val) => new MyDouble(val);
public static implicit operator MyDouble(MyInt val) => new MyDouble(val.Value);
public double Value { get; }
}
...
public void DoIt()
{
Console.WriteLine(ToString('A')); // CS0121
Console.WriteLine(ToString(1)); // now compiles :-)
}
Я предполагаю, что это работает, потому что механизм разрешения теперь считает, что преобразование в myDouble теперь выполняется по маршруту 1 -> myInt ->> myDouble, и это не может произойти неявно, поскольку для этого требуется два пользовательских преобразования. В том же духе я могу ToString('A') решить проблему правильно, добавив еще два неявных преобразования: MyChar в myDouble и MyChar в myInt.
Это нормально, так как оно отражает неявные преобразования, которые происходят между символами char, int и double. Но может ли кто-нибудь объяснить мне, почему исходный код, опубликованный выше, не будет компилироваться без дополнительных преобразований так, как мог бы понять простой мозг, подобный моему?
Комментарии:
1.A
Charможет быть неявно приведено к anInt. Anintможет быть неявно приведено кdouble. Учитывая неявные приведения кMyтипам, это означает, чтоToString('A')это может быть обработано обоимиToStringметодами. Вы можете удалить всеToString()методы, кромеToString(MyInt), и код все равно будет работать2. Что ты пытаешься сделать? Вы пробуете что-то или это упрощенный случай реальной проблемы?
3. @PanagiotisKanavos Это самое простое сокращение проблемы, которую я нашел в своем коде. Я хочу представить полный API, поэтому у меня нет роскоши удалять методы. Я хочу использовать перегруженное имя, так как в сознании пользователя операция-это одно и то же, независимо от типа, на котором она выполняется. Чего я не понимаю, так это почему символ преобразования -> MyChar не выбран в качестве однозначного преобразования, поскольку он ближе, чем символ ->> int ->>> myInt.
4. опишите реальную проблему в самом вопросе. Ни одно из преобразований не находится ближе, чем другое. Все они требуют неявных приведений, поэтому ни одно из них не ближе другого. Для этих примеров существует несколько методов, которые могут быть вызваны после неявных приведений.
5.
as in the user's mind the operation is the same thing, irrespective of the type its operating on.почему бы тогда не использовать общий метод? Приведите пример реальной проблемы. Вы можете использовать общий интерфейс для всех типов, использовать общие методы или использовать какой-либо другой трюк
Ответ №1:
A char может быть неявно приведено к an int . An int может быть неявно приведено к double . Учитывая неявные приведения к My типам, это означает, что ToString('A') это может быть обработано обоими ToString методами.
Вы можете удалить все ToString() методы, кроме ToString(MyInt) , и код все равно будет работать:
public class ConversionTests
{
public void DoIt()
{
Console.WriteLine(ToString('A'));
Console.WriteLine(ToString(1));
}
private static string ToString(MyInt i) => $"{i.Value}";
}
Это напечатало бы :
65
1
У меня проблема —
System.Net.Http.HttpClientExtensions.PostAsJsonAsync (System.Net.Http.HttpClient, string, T, System.Threading.CancellationToken) и System.Net.Http.Json
private async Task Add()
{
using (var msg = await Http.PostAsJsonAsync<Feedback>("/api/feedbacks", newcust, System.Threading.CancellationToken.None))
{
if (msg.IsSuccessStatusCode)
{
custs.Add(await msg.Content.ReadFromJsonAsync<Feedback>());
newcust.title = newcust.rating = newcust.comment = null;
}
}
if (ValidReCAPTCHA)
{
var response = await reCAPTCHAComponent.GetResponseAsync();
try
{
ServerVerificatiing = true;
StateHasChanged();
await Http.PostAsJsonAsync("/api/sample", new SampleAPIArgs { reCAPTCHAResponse = response });
Navigation.NavigateTo("/valid");
}
catch (HttpRequestException e)
{
await JS.InvokeAsync<object>("alert", e.Message);
ServerVerificatiing = false;
StateHasChanged();
}
}
}
Скриншот Изображение
2 ответа
Лучший ответ
Использовать
System.Net.Http.Json.HttpClientJsonExtensions.PostAsJsonAsync
Вместо того
System.Net.Http.HttpClientExtensions.PostAsJsonAsync
Вам могут понадобиться некоторые из них, используя:
using System.Net.Http.Json;
using System.Net.Http;
using System.Text.Json;
using System.Text;
using System.Text.Json.Serialization;
Удалите любые ссылки на System.Net.Http.HttpClientExtensions
Ниже приведен код для установки System.Net.Http.Json, если он не установлен
Install-Package System.Net.Http.Json -Version 5.0.0
2
enet
5 Мар 2021 в 11:05
Метод Http.PostAsJsonAsync находится в двух пространствах имен — посмотрите, что на самом деле говорится в сообщении об ошибке.
Вы должны уточнять имя, чтобы компилятор знал, какое из них вы хотите использовать. В противном случае вы должны удалить один из конфликтующих using.
Как сказали PMF и Klaus в своих комментариях — пожалуйста, публикуйте код, а не скриншоты.
0
Claus H
5 Мар 2021 в 10:39
C# Compiler Error
CS0121 – The call is ambiguous between the following methods or properties: ‘method1’ and ‘method2′
Reason for the Error
You will receive this error when you usually call one of the overloaded method and the C# compiler is not able to call it because of the conflict with the parameters caused by implicit conversion.
For example, let’s have a look at the below C# code snippet.
namespace DeveloperPublishNamespace
{
public class DeveloperPublish
{
public static void Method1(int input1,double input2)
{
}
public static void Method1(double input1,int input2)
{
}
public static void Main()
{
Method1(5,5);
}
}
}
This contains 2 overloaded functions with different parameter type. When this function is called with the parameter 5,5, it results with the below error.
Error CS0121 The call is ambiguous between the following methods or properties: ‘DeveloperPublish.Method1(int, double)’ and ‘DeveloperPublish.Method1(double, int)’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

C# compiler was not able to identify which overloaded method to call because of the values that is passed which results in the implicit conversion.
Solution
There are plenty of ways in which you can avoid this error. You can either specify the parameter type with the explicit conversion so that the implicit conversion doesn’t take place or possibly use a named arguments.
|
kservice 0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
||||||||
|
1 |
||||||||
|
15.08.2022, 14:34. Показов 1289. Ответов 12 Метки forms, msdn, програмированние (Все метки)
При использовании примера кода из MSDN возникло множество ошибок. В VS 2022 cоздал проект Windows Forms (Microsoft) C# и вставил код в Form1.cs Ошибки: и 7 ошибок в разных строках Код из Form1.cs и Form1.Designer.cs прилагаю Кликните здесь для просмотра всего текста
Код Form1.Designer.cs Кликните здесь для просмотра всего текста
В чем проблема и как устанить?
0 |
|
Администратор
15668 / 12629 / 5003 Регистрация: 17.03.2014 Сообщений: 25,712 Записей в блоге: 1 |
|
|
15.08.2022, 15:53 |
2 |
|
kservice, проблемы перечислены в ошибках компиляции. Во-первых, вам не нужно было копировать код класса Program. Во-вторых, код метода InitializeComponent из Form1.cs нужно аккуратно объединить с InitializeComponent из Form1.Designer.cs, после чего удалить первый.
1 |
|
0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
|
|
15.08.2022, 21:17 [ТС] |
3 |
|
Помогло частично Form1. cs Form1.Designer.cs Не знаю, насколько это «аккуратно»:
0 |
|
Администратор
15668 / 12629 / 5003 Регистрация: 17.03.2014 Сообщений: 25,712 Записей в блоге: 1 |
|
|
15.08.2022, 22:21 |
4 |
|
kservice, — удалите поле components в Form1.cs
1 |
|
0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
|
|
16.08.2022, 11:14 [ТС] |
5 |
|
Спасибо, получилось. Возникает риторический вопрос: зачем такие примеры, которые надо допиливать? Миниатюры
0 |
|
9805 / 5970 / 1410 Регистрация: 25.05.2015 Сообщений: 18,193 Записей в блоге: 14 |
|
|
16.08.2022, 13:22 |
6 |
|
kservice, можете ссылку на статью показать?
0 |
|
0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
|
|
16.08.2022, 14:17 [ТС] |
7 |
|
https://docs.microsoft.com/ru-… esktop-6.0 Сразу после текста «Примеры
0 |
|
9805 / 5970 / 1410 Регистрация: 25.05.2015 Сообщений: 18,193 Записей в блоге: 14 |
|
|
16.08.2022, 14:34 |
8 |
|
kservice, не, ссылку именно на статью в msdn. Добавлено через 9 минут
0 |
|
Администратор
15668 / 12629 / 5003 Регистрация: 17.03.2014 Сообщений: 25,712 Записей в блоге: 1 |
|
|
16.08.2022, 14:54 |
9 |
|
зачем такие примеры, которые надо допиливать? Очевидно предполагается минимальное знакомство с Windows Forms и C#. А во вторых, автор примера явно стремился показать всё в рамках одного файла.
как добавить вручную (без применения конструктора) пункт субменю Посмотрите как добавляются существующие и сделайте по аналогии. Подсказка — смотрите Initialize методы.
0 |
|
0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
|
|
16.08.2022, 15:35 [ТС] |
10 |
|
Посмотрите как добавляются существующие и сделайте по аналогии. Мне бы ваши знания. Смотрел и пробовал, и не один раз. Не получается. Пункты переименовать и удалить могу, добавить — нет. Саму идеологию понять не могу. Если подскажите более подробно — буду благодарен. kservice, не, ссылку именно на статью в msdn. Я код брал именно по ссылке, решил, что это и есть MSDN. Как получить ссылку нименно на статью в msdn — не наю
0 |
|
Andrey-MSK 1646 / 1121 / 243 Регистрация: 14.08.2018 Сообщений: 3,673 Записей в блоге: 4 |
||||||||||||
|
17.08.2022, 08:37 |
11 |
|||||||||||
|
kservice, Вот так выглядит пример, по вашей ссылке, в проекте, который создаёт студия
Form1.Designer.cs
Program.cs
1 |
|
0 / 0 / 0 Регистрация: 05.03.2016 Сообщений: 62 |
|
|
17.08.2022, 12:24 [ТС] |
12 |
|
Спасибо, буду разбираться. Добавлено через 3 часа 10 минут
Вот так выглядит пример, по вашей ссылке, в проекте, который создаёт студия Я тоже делал с помощью студии, а разница громадная.
0 |
|
Andrey-MSK 1646 / 1121 / 243 Регистрация: 14.08.2018 Сообщений: 3,673 Записей в блоге: 4 |
||||||||
|
17.08.2022, 16:19 |
13 |
|||||||
|
Растолкуйте, как так получается? Что получается? Я просто раскидал ту портянку из документации по нужным файлам проекта и всё. В файле
и
Вот и всё…
1 |

