简体   繁体   English

在IIS上托管时拆分字符串会引发InvalidOperationException

[英]Splitting a string throws InvalidOperationException when hosting on IIS

I wrote the following code: 我写了以下代码:

private string makeMailContents(Klant klant, Mail mail)
{
    var builder = new BodyBuilder();
    var path = Path.Combine("wwwroot/trackers/track_open.png");
    var img = builder.LinkedResources.Add(path);
    byte[] data = Convert.FromBase64String(mail.Content);
    string decoded = Encoding.UTF8.GetString(data);
    string code;
    string final = "";
    Regex regex = new Regex(@"\[([^]]*)\]");

    img.ContentId = MimeUtils.GenerateMessageId();

    var splitContent = decoded.Split(' ');

    foreach(string word in splitContent) // this is line 265
    { 
            if (word.Contains('[') && word.Contains(']'))
            {
                try
                {
                    code = Regex.Match(word, @"\[([^]]*)\]").Groups[1].Value.ToLower();
                    switch (code)
                    {
                        case "voornaam":
                            final += regex.Replace(word, klant.vnaam) + ' ';
                            break;
                        case "achternaam":
                            final += regex.Replace(word, klant.anaam) + ' ';
                            break;
                        case "naam":
                            final += regex.Replace(word, klant.vnaam + ' ' + klant.anaam + ' ');
                            break;
                        case "onderwerp":
                            final += regex.Replace(word, mail.Onderwerp + ' ');
                            break;
                        case "datum":
                            final += regex.Replace(word, DateTime.Now.ToString("dd-MM-yyyy") + ' ');
                            break;
                    }
                }
                catch (Exception ex)
                {
                    final += ex;
                }
            }
            else
            {
                final += word + ' ';
            }
    }
}

Whenever I run this code on my local machine and my test server it executes the code like it should without any exceptions. 每当我在本地计算机和测试服务器上运行此代码时,它便会像应该执行的代码一样毫无例外地执行代码。

But whenever I host this on my current live server it throws the following exception: 但是,每当我在当前的实时服务器上托管它时,它都会引发以下异常:

InvalidOperationException: Sequence contains no elements InvalidOperationException:序列不包含任何元素

And this exceptions keeps pointing towards the splitContent and it tells me that it doesn't contain elements. 而且这个异常一直指向splitContent ,它告诉我它不包含元素。 And yes, the mail.Content is filled with a valid base64 string, I checked both with fiddler and postman. 是的, mail.Content填充了有效的base64字符串,我同时检查了提琴手和邮递员。

Does anyone have the slightest clue of what's going on here? 有人对这里发生的事情有丝毫线索吗? I'm also not sure if it's the IIS settings or somehow my code. 我也不确定是IIS设置还是我的代码。 I normally have a colleague who manages the IIS but he is on vacation right now. 我通常有一个管理IIS的同事,但他现在正在休假。 Can someone help me out with this? 有人可以帮我这个忙吗?

This is the data the mail receives when called: 这是邮件在调用时收到的数据:

 {      
    "Onderwerp":"Dit is een test campagne",
    "afzender":1,
    "campagne":1,
    "Content":"PHA+RGl0IGlzIGVlbiB0ZXN0IG1hYXQ8L3A+Cg==",
    "docs":"['kamer2.jpg']",
    "template":null,
    "verzenddat":"8/17/18, 3:55 PM"
}

full exception: 完全例外:

System.InvalidOperationException: Sequence contains no elements
   at System.Linq.Enumerable.Last[TSource](IEnumerable`1 source)
   at lambda_method(Closure , QueryContext )
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_1`1.<CompileQueryCore>b__0(QueryContext qc)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Last[TSource](IQueryable`1 source)
   at MailerAPI.Mailer.Sender.makeMailContents(Klant klant, Mail mail) in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Mailer\Sender.cs:line 265
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at MailerAPI.Mailer.Sender.<sendMessage>d__7.MoveNext() in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Mailer\Sender.cs:line 161
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MailerAPI.Controllers.MailController.<Post>d__13.MoveNext() in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Controllers\MailController.cs:line 96
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

The exception also gets thrown when I replace the model properties with just a plain string. 当我仅用纯字符串替换模型属性时,也会引发异常。

UPDATE Whenever I run this code in my values controller to test the decoded.split(' ') it actually works. 更新每当我在值控制器中运行此代码以测试decoded.split(' ')它实际上都可以工作。 When I return the decoded.split(' ') I actually get an array of strings. 当我返回decoded.split(' ')我实际上得到了一个字符串数组。

So now I know that the problem only occurs within the method, which is located in a Sender class and being called in the MailerController, and it also only occurs in the current server. 因此,现在我知道问题仅出现在方法中,该方法位于Sender类中,并在MailerController中被调用,并且也仅在当前服务器中发生。

You appear to be making a call to .Last() at or through the code located at C:\\Users\\Hofkey\\Source\\Repos\\MailerAPI\\MailerAPI\\Mailer\\Sender.cs:line 265 . 您似乎正在通过或通过位于C:\\Users\\Hofkey\\Source\\Repos\\MailerAPI\\MailerAPI\\Mailer\\Sender.cs:line 265处的代码来调用.Last()

The Linq extension method .Last() demands that there is at least one item that it can grab. Linq扩展方法.Last()要求至少可以抓取一项。 To work around this requirement, you have various options: 要变通解决此要求,您有多种选择:

  • use .LastOrDefault() accompanied with appropriate null handling, or 使用.LastOrDefault()以及适当的null处理,或者
  • before using .Last() , first check with if (... .Any()) if it is OK to call .Last() . 在使用.Last()之前,首先检查if (... .Any())是否可以调用.Last()


For further reference, see LINQ Element Operations 有关更多参考,请参见LINQ元素操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 连接绑定字符串时出现InvalidOperationException - InvalidOperationException when concatenating bound string 序列化List的XmlSerializer的构造函数 <T> 与XmlAttributeOverrides一起使用时抛出InvalidOperationException - Constructor of a XmlSerializer serializing a List<T> throws an InvalidOperationException when used with XmlAttributeOverrides 属性存在时,EntityEntry.Property()引发InvalidOperationException - EntityEntry.Property() throws InvalidOperationException when property does exist 当属性中包含名称空间前缀时,XmlSerializer会抛出InvalidOperationException - XmlSerializer throws InvalidOperationException when having a namespace prefix in the attribute 不使用Select()子句中的匿名类型时,构建SqlExpression会引发InvalidOperationException - Building SqlExpression throws InvalidOperationException when not using anonymous type in Select() clause 在/不在[]内时拆分字符串 - Splitting a string on / when not within [ ] 托管到IIS时无法访问打印机 - Unable to access the printer when hosting to iis 在IIS中托管时无法获取用户位置 - Unable to get user location when hosting in IIS 最大抛出InvalidOperationException - Max throws InvalidOperationException WPF DependencyProperty引发InvalidOperationException - WPF DependencyProperty throws InvalidOperationException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM