Exception has been thrown by the target of an invocation как исправить

I have a website developed in ASP.Net 2.0 that is throwing the error

"Exception has been thrown by the target of an invocation" 

in the production environment. It was not throwing this error in development.

The source is ‘mscorlib’, and the stack trace says the error at

System.RuntimeMethodHandle._InvokeMethodFast.

The only thing I’ve changed since my last upload to production is that I’ve started using Membership controls (Login, LoginView), and have added a few more stored procedures and tables, etc. The membership depends upon a custom provider I’ve written.

Anybody have a clue why this could be happening?

Joel Coehoorn's user avatar

Joel Coehoorn

396k113 gold badges565 silver badges792 bronze badges

asked Mar 15, 2009 at 16:47

Donnie Thomas's user avatar

Donnie ThomasDonnie Thomas

3,8798 gold badges47 silver badges70 bronze badges

2

I’d suggest checking for an inner exception. If there isn’t one, check your logs for the exception that occurred immediately prior to this one.

This isn’t a web-specific exception, I’ve also encountered it in desktop-app development. In short, what’s happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that’s being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.

If you haven’t already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.

Good luck!

answered Mar 15, 2009 at 16:51

Greg D's user avatar

4

This can happen when invoking a method that doesn’t exist.

Brian Webster's user avatar

Brian Webster

29.9k48 gold badges150 silver badges225 bronze badges

answered Aug 4, 2010 at 4:06

Casey Burns's user avatar

Casey BurnsCasey Burns

1,20312 silver badges15 bronze badges

2

I know its kind of odd but I experienced this error for a c# application and finally I found out the problem is the Icon of the form! when I changed it everything just worked fine.

I should say that I had this error just in XP not in 7 or 8 .

answered Mar 9, 2013 at 7:50

mohammad sepehri's user avatar

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

answered Sep 13, 2019 at 7:04

Kms's user avatar

KmsKms

1,0562 gold badges10 silver badges27 bronze badges

' Get the your application's application domain.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain 

' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExHandler 

' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler 

Private Sub MYExnHandler(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs) 
Dim EX As Exception 
EX = e.ExceptionObject 
Console.WriteLine(EX.StackTrace) 
End Sub 

Private Sub MYThreadHandler(ByVal sender As Object, _
ByVal e As Threading.ThreadExceptionEventArgs) 
Console.WriteLine(e.Exception.StackTrace) 
End Sub

' This code will throw an exception and will be caught.  
Dim X as Integer = 5
X = X / 0 'throws exception will be caught by subs below

Miroslav Javorský's user avatar

answered Jun 25, 2010 at 5:23

abc's user avatar

1

This error occurs to me due to I have not set my Project as StartUp Project

When I set my current project to Set As Start-Up Project then it gone.

answered Apr 2, 2019 at 8:24

shaishav shukla's user avatar

I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.

answered Jan 20, 2016 at 20:55

Greg Sipes's user avatar

Greg SipesGreg Sipes

6836 silver badges16 bronze badges

This is may have 2 reasons

1.I found the connection string error in my web.config file
i had changed the connection string and its working.

  1. Connection string is proper then check with the control panel>services>
    SQL Server Browser > start or not

answered Jan 24, 2017 at 6:09

Sameer Bahad's user avatar

my problem was that i didnt put the connection string in the right place in the appsettings.json it was inside IIS Express object then i moved it inside profiles object it didnt work as well the i fixed the problem by putting it inside the appsettings.json { here }

answered May 12, 2022 at 7:23

elad baruch's user avatar

1

Got same error, solved changing target platform from «Mixed Platforms» to «Any CPU»

answered Aug 6, 2018 at 21:19

Jaime Vasquez's user avatar

In my case, this happened due to choosing the option to publish as a single file in VS (.NET 5 console app), once I changed it to publish normally the exception was gone.

answered Mar 2, 2021 at 9:10

Meshal's user avatar

MeshalMeshal

32 silver badges3 bronze badges

I got this error after I tried to add a new controller in the Controller folder but the connection string was placed inside the entityFramework tag in Web.config file.

answered Apr 2, 2021 at 23:01

CSharp4eto's user avatar

CSharp4etoCSharp4eto

1471 silver badge6 bronze badges

For me, it happens when there is an internal call to another server and that server is not answering in a logical time or the configuration to call it is wrong. I fixed the problem of connecting to another server, then I received the correct data from that server and the function that was responsible for calling that server is working properly then I do not receive that error.

Ajay2707's user avatar

Ajay2707

5,6566 gold badges40 silver badges58 bronze badges

answered Apr 29, 2021 at 14:41

Beny Sad's user avatar

Beny SadBeny Sad

2903 silver badges14 bronze badges

I edited the validation field, the error was resolved.

builder.Property(x => x.Name)**.UseIdentityColumn()**.HasMaxLength(200);  
builder.Property(x => x.Name)**.IsRequired()**.HasMaxLength(200);

answered Mar 13, 2022 at 20:11

Görkem's user avatar

In my case I just update Oracle.ManagedDataAccess.Core package from 2.19.60 to 3.21.61

answered Jul 13, 2022 at 11:28

Consule's user avatar

ConsuleConsule

95910 silver badges12 bronze badges

I had the same problem.
I was trying to create a report from C# and it wasn’t checking if the field is empty or whitespace.

I add Exception.

answered Dec 23, 2022 at 11:37

Georgios Loudaros's user avatar

When debugging and no InnerException found it can be handy to hit F5 (continue) until it hits another Exception. Or if it drops out entirely you can then check the Output window for more details.

answered Jan 18 at 12:11

DevDave's user avatar

DevDaveDevDave

6,65012 gold badges64 silver badges98 bronze badges

In my case just this worked:

dotnet ef migrations add MyMigrationName --startup-project {your .csproj} --context {your context}

answered May 10 at 5:55

akbar's user avatar

akbarakbar

6156 silver badges12 bronze badges

This can have two reasons

  1. Use HasForeignKey when selecting the WithMany method
builder.HasOne(m => m.Model).WithMany(m => m.ParentModel).HasForeignKey(m => m.Number)
  1. Insert IsRequired for number
builder.Property(p => p.Number).IsRequired();

You must delete these two items

answered 7 hours ago

رضا محمدپور's user avatar

New contributor

رضا محمدپور is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

In this guide, we will walk you through the process of resolving the «Exception has been thrown by the target of an invocation» error. This error is common in .NET applications and can be caused by various reasons. By following the steps provided, you should be able to identify and fix the issue in your application.

Table of Contents

  1. Understanding the Error
  2. Step-by-Step Solution
  3. FAQ

Understanding the Error

The «Exception has been thrown by the target of an invocation» error occurs when an application or library attempts to call a method using reflection, but the method throws an exception. The .NET runtime will wrap the original exception in a TargetInvocationException.

Here’s an example of the error message:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.

Step-by-Step Solution

To resolve the «Exception has been thrown by the target of an invocation» error, follow these steps:

Identify the source of the exception: The first step is to identify the source of the exception. Check the error message to find the original exception type (e.g., System.NullReferenceException) and the method that threw the exception.

Check the InnerException property: The TargetInvocationException object has an InnerException property that contains the original exception. Examine this property to find more information about the error, such as the stack trace and any custom error messages.

try
{
    // Call a method using reflection
}
catch (TargetInvocationException ex)
{
    // Log the inner exception details
    Console.WriteLine("Inner Exception: " + ex.InnerException);
}

Debug the application: Use a debugger to step through your code and identify the exact line where the exception is thrown. This will help you understand the root cause of the issue.

Fix the issue: Once you have identified the root cause of the exception, you can fix the issue in your code. This might involve checking for null references, handling exceptions properly, or ensuring that necessary resources are available.

Test the application: After making the necessary changes, test the application to ensure that the issue is resolved and no other errors occur.

FAQ

1. When does the ‘Exception has been thrown by the target of an invocation’ error occur?

This error occurs when an application or library attempts to call a method using reflection, but the method throws an exception. The .NET runtime will wrap the original exception in a TargetInvocationException.

2. What is a TargetInvocationException?

TargetInvocationException is an exception that is thrown by the .NET runtime when a method called using reflection throws an exception. It wraps the original exception in its InnerException property.

3. How can I find the original exception that caused the TargetInvocationException?

You can find the original exception by examining the InnerException property of the TargetInvocationException object.

4. Can this error occur in non-.NET applications?

Yes, this error can occur in other programming languages and frameworks that support calling methods using reflection. The specific exception type and error message may vary depending on the language and runtime environment.

5. How can I prevent the ‘Exception has been thrown by the target of an invocation’ error from occurring?

To prevent this error, ensure that your code is properly handling exceptions and validating input before calling methods using reflection. Additionally, you should test your application thoroughly to identify and fix any potential issues before deployment.

Related links:

  • Microsoft Docs: TargetInvocationException Class
  • Microsoft Docs: Exception Handling (C#)

An exception has been thrown by the target of an invocation occurs because you don’t have administrator rights, or you want to access non-existent data. If you’re seeing this error in your work environment, and you can’t continue your work. In this article, you’ll learn more about the error and how to fix it.the exception has been thrown by the target of an invocation

From our explanation, you’ll know the answer to the question: what does exception has been thrown by the target of an invocation mean?

Contents

  • Why Is There an Exception From the Target of an Invocation?
    • – You Want to Access Non-existent Data
    • – You Don’t Have Administrator Rights on Your Computer
    • – Your System Does Not Have “.Net Framework”
    • – Your “Path” Environment Variable Is Too Long
    • – You Have Outdated Software
  • How To Fix an Exception That’s Thrown by the Target of an Invocation
    • 1. Double-check Your Data for Wrong Information and Typos
    • 2. Run Your Application With Administrator Rights
    • 3. Install “.Net Framework” After Updating Sql Server
    • 4. Shorten the Path Environment Variable on Your Computer
    • 5. Update Your Software
  • Conclusion

Why Is There an Exception From the Target of an Invocation?

There is an exception from the target of an invocation because of the following:

  • You want to access non-existent data
  • You don’t have administrator rights on your computer
  • Your system does not have NET Framework
  • Your PATH environment variable is too long
  • You have outdated software

– You Want to Access Non-existent Data

Any attempt to access non-existent or out-of-range data will lead to the exception has been thrown by the target of an invocation” C# error. This applies if you’re working with “Xamarin.Forms” using a C# codebase or UiPath. For the latter, an error will occur if you want to assign a value to a non-existent column in your table. For “Xamarin.Forms”, if you have a list, an error will occur if you try to edit an index that’s out of range.

– You Don’t Have Administrator Rights on Your Computer

By default, on a Windows system, you can run most applications without admin rights. But, there is a limit to what you can do with such a system. If it’s Visual Studio, you can run into the exception has been thrown by the target of an invocation Visual Studio 2019 error. First, this is not a bug in Windows, it’s how it works to prevent malicious applications and “ordinary” users from gaining admin rights.

As it stands, if you’re getting the error, it’s because Windows considers your account as an ordinary user account. What’s more, if you have User Account Control (UAC) turned “on” in the Control Panel, it can lead to the error as well. That’s because UAC has different limits that permit what you (or your application) can do on the system.

– Your System Does Not Have “.Net Framework”

The “.NET Framework” is an essential part of a system if you want to run applications like SQL Server or Visual Studio. Without it, any attempt to run either application will result in an error. For example, you can have an older version of Windows Server from 2008 running alongside SQL Server Management Studio. Everything will work fine, but that’ll not be the case when you update the Windows Server to a newer version.Exception Has Been Thrown by the Target of an Invocation Causes

This newer version will require the appropriate “.NET Framework” before you can open the Server Studio. If you don’t have it installed on your computer, that’s when you’ll get the invocation error. This happens because when you start the server studio, it’ll do a background check to ensure it has what it needs to work. Without the “.NET Framework”, this test will fail, and you’ll get an error.

– Your “Path” Environment Variable Is Too Long

On a normal day, the “Path” environment variable should not exceed 2,047 characters. But, if it exceeds 2,047, you’ll run into the exception invocation error. You’ll notice this error if you try to open Visual Studio and SQL Server Management Studio. Now, to see if the “Path” environment variable is the cause of the error on your system, do the following:

  1. Press “Ctrl” and “R” on your keyboard at the same time.
  2. Type the following without quotes: “control system”.
  3. Click the “OK” button or press “enter” on your keyboard.
  4. Click on “Advanced system settings”.
  5. Choose “Environment Variables”
  6. Check the “Path” variable under “System variables”

If the value of the “Path” variable is too long on your system, it’s the cause of the error. What’s more, you can confirm this by checking your system registry using the following:

  1. Press “Ctrl” and “R” on your keyboard at the same time.
  2. Type the following without quotes: “regedit”.
  3. Click “OK” or press the enter key on your keyboard.
  4. Open “HKEY_LOCAL_MACHINE”, then do the following:
    1. Expand “SYSTEM” followed by “CurrentControlSet”.
    2. Expand the “Control” key, followed by “Session Manager”.
    3. Check the “Environment” key and inspect the “Path” variable.

– You Have Outdated Software

Outdated software can also cause an exception from the target of an invocation. For example, your setup can consist of SQL Server 2017 and SQL Server Management Studio 2014. From this, you can conclude the management studio has a lesser version number than the server itself. Now, if you try to connect the server through the studio, you’ll run into the error that we are talking about.

The reason is simple: backward compatibility. Microsoft’s applications don’t always work together if one is newer than the other. So, when you see a message about an “exception”, there is a sign that’s software compatibility. But, now that you know this, let’s discuss how to fix it in the next section.

How To Fix an Exception That’s Thrown by the Target of an Invocation

You can fix an exception that’s Thrown from the target of an invocation using any of the following:

  • Double-check your data for wrong information and typos
  • Run your application with administrator rights
  • Install “.NET Framework” after updating SQL server
  • Shorten the Path environment variable on your computer
  • Update your software

1. Double-check Your Data for Wrong Information and Typos

An inspection of your setup for typos is a way to fix the exception has been thrown by the target of an invocation UiPath error. These typos can be a wrong column name in your table. The following will help you hunt it down:

  1. Check the column name and ensure it’s correct
  2. Ensure the column exists
  3. Ensure your data does not have identical column names.

2. Run Your Application With Administrator Rights

When you run your application as an administrator, you can solve the exception has been thrown by the target of an invocation – SSIS script task error. Now, if you maintain a package that uses an SSIS script task, and this error occurs, do the following:

  1. Wrap your code in a “try/catch” block.
  2. Throw an exception message to know what’s going wrong.
  3. Inspect the exception message for “UnauthorizedAccessException”

If you encounter “UnauthorizedAccessException”, you’ll need to get the right permissions.Meanwhile, if you’re facing this error in Visual Studio, you can run it as an administrator. The following is how you do it:

  1. Right-click the Visual Studio icon on your desktop.
  2. Click “Run as administrator”.

3. Install “.Net Framework” After Updating Sql Server

The correct “.NET Framework” will fix the exception has been thrown by the target of an invocation SQL error. You can get a “.NET Framework” from Microsoft using the following steps:Exception Has Been Thrown by the Target of an Invocation Fixes

  1. Visit the “NET Framework installation guide” on Microsoft Ignite website.
  2. Locate the section that says “Supported Windows version”.
  3. Select the link to download the “.NET Framework” based on your operating system.

After downloading, install the “.NET Framework” and everything will work fine.

4. Shorten the Path Environment Variable on Your Computer

The “Path” environment variable on your Windows computer should not exceed 2,047. If yours has exceeded this range, here is how you can reduce it:

  1. Press “Ctrl” and “R” on your keyboard at the same time.
  2. Type the following without quotes: “control system”.
  3. Click on “Advanced system settings”.
  4. Choose “Environment Variables”
  5. Click the “Path” variable under “System variables”.
  6. Reduce the number of characters below 2,047.
  7. Click “Apply” and close the dialog window.
  8. Reboot your computer.

5. Update Your Software

Updated software saves you lots of trouble and hours of debugging. So, if you have older versions of the following software, update them immediately:

  • Visual Studio
  • SQL Server Management Studio

For both software, you can get their updated version from Microsoft’s website.

Conclusion

This article explained why the target of an invocation throws an exception in your application. Besides that, we explained how to solve it, and we’ll leave you with the following key points:

  • If you don’t have administrator rights, you can run into the exception invocation error in Visual Studio.
  • A long “Path” environment variable can cause an exception from the target of an invocation.
  • You can stop an exception from the target of an invocation with regular software updates.
  • When you update your SQL Server, install an updated “.NET” Framework to prevent exception errors.

At this stage, you know how to stop your application from throwing an exception from the target of an invocation. Print our article and place it where you can look it up with ease when you run into this error in the future.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Remove From My Forums
  • Question

  • Hi,

    (VS 2005, Beta 2)

    I get the error «Exception has been thrown by the target of an invocation» when I try to open any of the test windows using «Test|Windows|Test View» or any similar approach.

    I created a new solution a while ago and added some unit tests. Everything was working great, until now…

    Anybody have any suggestions?

    Thanks,
    Tor Langlo

Answers

  • Hello,

    I don’t think deleting vsmdi and testrunconfig files would help.
    But yes, if you unload the solution, you should be able to bring up the windows. The problem comes in when your solution *is* the one that contains test projects which you want to execute tests on.
    In any case, if the suggestion or workaround does not work for you, please let me know. Thanks!

    Winnie

This was the only thing I could see that looked like it may be of some value.

14:07:48.214 Debug [ 9] WorkItemDispatcher: Directly executing RegisterAndActivateNewUser
14:11:33.944 Error [ 8] TestProgressReporter: Exception processing POMAuctivaTest.TestSuite.NewUserTestSuite<FirefoxDriver>.RegisterAndActivateNewUser
System.Runtime.Remoting.RemotingException: Object '/3742bc21_6eb6_4710_861d_d06e30e9469f/gzkc3ewv3ziqu3co_sd1geil_1.rem' has been disconnected or does not exist at the server.

Server stack trace: 
   at System.Runtime.Remoting.Channels.ChannelServices.CheckDisconnectedOrCreateWellKnownObject(IMessage msg)
   at System.Runtime.Remoting.Channels.ChannelServices.DispatchMessage(IServerChannelSinkStack sinkStack, IMessage msg, IMessage& replyMsg)

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 NUnit.Engine.ITestEventListener.OnTestEvent(String report)
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [1]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(String eventArgument)
   at NUnit.Framework.Internal.TestProgressReporter.TestFinished(ITestResult result)
14:11:35.213 Info  [ 9] TestWorker: Worker#STA_NP executing PostSaleTestSuite<ChromeDriver>
14:11:35.217 Error [ 8] TestProgressReporter: Exception processing POMAuctivaTest.TestSuite.NewUserTestSuite<FirefoxDriver>
System.Runtime.Remoting.RemotingException: Object '/3742bc21_6eb6_4710_861d_d06e30e9469f/gzkc3ewv3ziqu3co_sd1geil_1.rem' has been disconnected or does not exist at the server.

Понравилась статья? Поделить с друзьями:
  • Как найти ставку дисконтирования для проекта
  • Как составить претензию на застройщика об устранении недостатков
  • Мутные скины в кс го как исправить
  • Как правильно составить заявление при избиении
  • Как в ворде найти нужную фразу