gpt4 book ai didi

c# - 仅在生产环境中抛出 MulticastDelegate 异常

转载 作者:行者123 更新时间:2023-11-30 14:08:52 28 4
gpt4 key购买 nike

我有一个仅在生产环境中发生的非常奇怪的问题。异常有消息

"Delegate to an instance method cannot have null 'this'".

抛出异常的方法非常简单,并且工作了很长时间,所以问题一定是环境中的模糊依赖,或者类似的东西......

我使用托管在 Azure 中的 ASP.NET Web API, Controller 的操作方法通过 AJAX 执行。

下面是抛出异常的代码:

public class BlacklistService : IBlacklistService
{
public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}
}

这是堆栈跟踪的相关部分:

at System.MulticastDelegate.ThrowNullThisInDelegateToInstance() 
at System.MulticastDelegate.CtorClosed(Object target, IntPtr methodPtr)
at MyApp.Business.Services.BlacklistService.Verify(String blacklist, String message)
at MyApp.Business.Services.ContactMessageFactory.GetVerifiedStatus(String mensagem)
at MyApp.Business.Services.ContactMessageFactory.GetMailMessage(ContactForm contactForm)
at MyApp.Business.ContactEmailService.Send(ContactForm contactForm)

有人能找出这个异常的可能原因吗?提前致谢。

最佳答案

问题在于 message实际上是null 。您可以很容易地重现这一点:

void Main()
{
Verify("hello", null);
}

public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}

发生的情况是message.Contains被传递到Func<string, bool>构造函数通过方法组转换,它看起来像这样:

Func<string, bool> func = ((string)null).Contains;
return !split.Any(func);

这就是导致MulticastDelegate的原因发疯了。您还可以在生成的 IL 中看到:

IL_0028:  ldftn       System.String.Contains
IL_002E: newobj System.Func<System.String,System.Boolean>..ctor
IL_0033: call System.Linq.Enumerable.Any

为了避免这种情况发生,请确保您也将检查消息设为空:

public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
if (string.IsNullOrEmpty(message)) return false;

var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}

关于c# - 仅在生产环境中抛出 MulticastDelegate 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593157/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com