簡體   English   中英

僅在生產環境中拋出MulticastDelegate異常

[英]MulticastDelegate exception being thrown only in production environment

我有一個非常奇怪的問題,只發生在生產環境中。 該例外有消息

“委托給一個實例方法不能為'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)

有人可以弄清楚這個例外的可能原因嗎? 提前致謝。

問題在於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);
}

具有空的代表this是該方法string.Contains()用於向端部,其使用您的message變量作為this指針。 換句話說,在message為空時進行調用。

消息為空時失敗。 可以用這個

return !split.Any(part => (message != null && message.Contains(part)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM