加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:27:21 所属栏目:百科 来源:网络整理
导读:我有一个非常奇怪的问题,只发生在生产环境中. 该例外有消息 “Delegate to an instance method cannot have null ‘this'”. 抛出异常的方法非常简单,并且工作了很长时间,所以 问题必须是环境中的模糊依赖,或类似的东西…… 我正在使用Azure中托管的ASP.NET
我有一个非常奇怪的问题,只发生在生产环境中.
该例外有消息

“Delegate to an instance method cannot have null ‘this'”.

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

我正在使用Azure中托管的ASP.NET Web API,控制器的操作方法是通过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)

有人可以弄清楚这个例外的可能原因吗?提前致谢.

解决方法

问题在于消息实际上是空的.你可以很容易地重现这个:

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读