Splitting a string throws InvalidOperationException when hosting on IIS - c#

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
And this exceptions keeps pointing towards the splitContent and it tells me that it doesn't contain elements. And yes, the mail.Content is filled with a valid base64 string, I checked both with fiddler and postman.
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. I normally have a colleague who manages the IIS but he is on vacation right now. 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. When I return the decoded.split(' ') I actually get an array of strings.
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.

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.
The Linq extension method .Last() demands that there is at least one item that it can grab. To work around this requirement, you have various options:
use .LastOrDefault() accompanied with appropriate null handling, or
before using .Last(), first check with if (... .Any()) if it is OK to call .Last().
For further reference, see LINQ Element Operations

Related

Jira .NET SDK: issue.Savechange() throw unknown exception

The .NET program I used to create Jira issues automatically failed to save the new created issue recently. The tool was working perfectly until a few days ago, so I guess the problem might be on the Jira server side. See the attached pics for exception details. What causes this exception? thanks.
The problem is resolved after removing following code, weird.
//new_issue.Priority = "None";
I tried following ways to set priority, but they both triggers that exception?
var new_issue = jira.CreateIssue("THINPRO");
new_issue.Components.Add("Security");
new_issue.Type = "Bug";
new_issue.Summary = "test;
new_issue.Description = "test;
/ set priority based on CVSS score use priority id
//1 = Highest 2 = High 3 = Medium 4 = Low 5 = Lowest 6 = (not used) 7 = None
if (score <= 0.0)
new_issue.Priority = "7";
else if (score >= 7.0)
new_issue.Priority = "2" ;
else if (score <= 4.0)
new_issue.Priority = "4";
else
new_issue.Priority = "3";
new_issue.SaveChanges();
// set priority based on CVSS score use priority name
if (score <= 0.0)
new_issue.Priority = "None";
else if (score >= 7.0)
new_issue.Priority = "High";
else if (score <= 4.0)
new_issue.Priority = "Low";
else
new_issue.Priority = "Medium";
new_issue.SaveChanges();
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.Security.Authentication.AuthenticationException: Response Content:
at Atlassian.Jira.Remote.JiraRestClient.GetValidJsonFromResponse(IRestRequest request, IRestResponse response)
at Atlassian.Jira.Remote.JiraRestClient.<ExecuteRequestAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Atlassian.Jira.Remote.JiraRestClient.<ExecuteRequestAsync>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Atlassian.Jira.Remote.IssuePriorityService.<GetPrioritiesAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Atlassian.Jira.IssuePriority.<GetEntitiesAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Atlassian.Jira.JiraNamedEntity.<LoadIdAndNameAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Atlassian.Jira.Issue.<ToRemoteAsync>d__158.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Atlassian.Jira.Issue.SaveChanges()
The value None is probably an invalid value.
In most (and default) Jira configuration, you cannot empty the Priority field. It's the system field and it must have a value from predefined list (usually something like Blocker, Critical, Major, Minor, Trivial).

ITfoxtec.Identity.Saml2 Invalid URI Issue

When i use <TargetFramework>net462</TargetFramework> for my Okta SAML implementation this throw a Invalid URL when it this new Saml2AuthnRequest(config); but on my first try using this code on netcoreapp3.1` this worked perfectly fine. Please let me know if i miss something thank you.
[HttpGet, AllowAnonymous]
public IActionResult Index(string returnUrl = null)
{
try
{
var config = GetSAMLConfig();
var binding = new Saml2RedirectBinding();
binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl ?? Url.Content("~/") } });
var request = new Saml2AuthnRequest(config);
return binding.Bind(request).ToActionResult();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private Saml2Configuration GetSAMLConfig()
{
var config = new Saml2Configuration();
config.AllowedAudienceUris.Add("Okta_SAML_Example");
config.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
config.RevocationMode = X509RevocationMode.NoCheck;
var entityDescriptor = new EntityDescriptor();
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri("https://---------.okta.com/app/exk2b0b7dibno7rOB5d6/sso/saml/metadata"));
if (entityDescriptor.IdPSsoDescriptor != null)
{
config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
config.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
}
else
{
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
return config;
}
Actual exception
System.UriFormatException: Invalid URI: The format of the URI could not be determined.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at ITfoxtec.Identity.Saml2.Configuration.Saml2IdentityConfiguration.GetAudienceRestriction(Boolean audienceRestricted, IEnumerable`1 allowedAudienceUris)
at ITfoxtec.Identity.Saml2.Configuration.Saml2IdentityConfiguration.GetIdentityConfiguration(Saml2Configuration config)
at ITfoxtec.Identity.Saml2.Saml2Request..ctor(Saml2Configuration config)
at ITfoxtec.Identity.Saml2.Saml2AuthnRequest..ctor(Saml2Configuration config)
at SAMLNet461.Controllers.HomeController.Index(String returnUrl) in D:\REPO\PELICAN\LOCAL\SAML.RND - CompanyAcccounts adjustment\SAML.Demo\SAMLNet461\Controllers\HomeController.cs:line 69
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
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 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__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__23.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__18.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__16.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.StaticFiles.StaticFileMiddleware.<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 code looks correct.
Maybe it is a TLS version issue.
An alternative solution is to download the metadata in your code and add the metadata string to the ITfoxtec Identity SAML 2.0 library:
var idPMetadataXml = "... downloaded metadata ...";
var entityDescriptor = new EntityDescriptor();
entityDescriptorReadIdPSsoDescriptor(idPMetadataXml);
...
Updated:
The error seams to be in relation to Audience Restriction:
config.AllowedAudienceUris.Add("Okta_SAML_Example");
The audience have to be a URI in a .NET Framework application. Plain text strings are only supported in .NET Core and .NET 5.0.
.NET Framework sample: https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/tree/master/test/TestWebApp
I had the same issue and it was caused by "GetAudienceRestriction() method". Changing issuer name from "application-name" to "https://application-name" helped. Don't forget to change your name on your Identity Provider side (Okta, Ping Identity etc.) consistently. Now exception is not thrown anymore.

ASP.NET Core ViewComponent Invocation: InvalidCastException

Here is what I have
I have a view component as
public class TestViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int param1, int param2)
{
return Content(param1.ToString() + param2);
}
}
And a controller as
public class HomeController : Controller
{
private Dictionary<string, object> _dict = new Dictionary<string, object>();
public IActionResult Index()
{
_dict = new Dictionary<string, object>() { ["param1"] = 100, ["param2"] = 200 };
return ViewComponent("Test", _dict)
}
public IActionResult Index1()
{
var obj = new { param1 = 100, param2 = 200 };
var objString = JsonConvert.SerializeObject(obj);
_dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(objString);
return ViewComponent("Test", _dict);
}
}
When I call the first Index action everything is good. It works as expected but when I call the Index1 action I get an error with the following stack trace
System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentInvoker.<InvokeAsyncCore>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentInvoker.<InvokeAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentHelper.<InvokeCoreAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewComponentResultExecutor.<ExecuteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
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.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__6.MoveNext()
It seems there is some issue after the Deserialization. The exception is thrown even before the InvokeAsync method of the view component is called.
I have been stuck on this for a while. Any help will be really appreciated.
Thanks.
The error message is pretty much telling what's happening here. The actual objects in the deserialized dictionary are Int64s, which the arguments expected by the ViewComponent are Int32 (also called int in C#).

How to properly handle Task Exception

I am trying to figure out how to properly handle some exceptions in a Task:
Calling Method:
Task<Branch3GInfo> getActive3GRoutersTask =
Task.Run(
() => CAS.Service.GetBranch3GInformationAsync(3)
);
try
{
Task.WaitAll(discoverRouterExtendedInfoTask, getActive3GRoutersTask);
}
catch(AggregateException aggEx)
{
StringBuilder sb = new StringBuilder();
sb.Append("Some problems occured on GetNodesInCriticalCondition(): \n");
foreach (var ex in aggEx.InnerExceptions)
{
sb.Append(ex.Message);
}
Trace.TraceError(sb.ToString());
}
var branch3gInfo = getActive3GRoutersTask.Result;
var branch3gInfo = getActive3GRoutersTask.Result; throws a System.Aggregate Exception.
Called method:
public async Task<Branch3GInfo> GetBranch3GInformationAsync(int searchDepth)
{
var branch3gInfo = await GetBranch3GInterfacesAsync();
var activeRoutersExtInfos = new List<CasApiRouterModelExtendedInfo>();
foreach (var netInterface in branch3gInfo.Branch3GActiveInterfaces)
{
try
{
var task = GetRouterExtendedInfoFromInterfaceAsync(netInterface, searchDepth);
var result = await task;
if (task.Status == TaskStatus.RanToCompletion && result != null)
{
activeRoutersExtInfos.Add(result);
}
else
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName + ".");
}
}
catch (Exception ex)
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName +
": \n" + ex.Message);
}
}
return new Branch3GInfo()
{
Branch3GActiveInterfaces = branch3gInfo.Branch3GActiveInterfaces,
Branch3GCapableInterfaces = branch3gInfo.Branch3GCapableInterfaces,
Branch3GActiveRouters = activeRoutersExtInfos.ToArray()
};
}
From my code, I am making the assumption that GetBranch3GInformationAsync() should be either executing the else clause which doesn't add the result to activeRoutersExtInfos, OR, it should be catching the exception. Why is it that the calling method throws a System.AggregateException if I am handling this in GetBranch3GInformationAsync()?
How do I go about fixing this so that any call to GetRouterExtendedInfoFromInterfaceAsync() that fails due to an exception is ignored, and so that it doesn't break my code?
UPDATE:
Stack trace for the InnerException in System.AggregateException ("The remote server returned an error: (500) Internal Server Error.")
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.CasApiRestCall.<ExecuteAsync>d__38.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Queries\CasApiRestCall.cs:line 294
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<RenderAndExecuteRestCallAsync>d__103.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 2516
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<QueryModelsFilterByAttributeNotDeviceOnlyAsync>d__51.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 1196
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 442
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInformationAsync>d__26.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 246
You can see from your call stack:
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext()
that it is the call to GetBranch3GInterfacesAsync that is failing, not the call to GetRouterExtendedInfoFromInterfaceAsync. GetBranch3GInterfacesAsync is called outside the try block, so naturally the exception will propagate.

Server cannot append header after HTTP headers have been sent uploading files

I get this exception intermittently in my asp.net mvc 5 c# web application:
Server cannot append header after HTTP headers have been sent.
It just happens uploading images to S3 method (Web Api Controller).
The presendrequestheaders in Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null &&
app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
The method that trigger the error:
[HttpPost]
[Route("UploadImageJSON")]
public IHttpActionResult UploadImageJSON(HttpRequestMessage request)
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count != 1) return BadRequest();
var postedFile = httpRequest.Files[0];
var contentType = postedFile.ContentType;
if (!contentType.Contains("image"))
{
return StatusCode(HttpStatusCode.NotAcceptable);
}
var keyUploadFiles = Constants.UrlS3Amazon +
S3.UploadToS3WithStream(postedFile.InputStream, contentType);
return Json(JsonConvert.SerializeObject(keyUploadFiles));
}
EDIT: More information... I have my Web App hosted in Elastic BeanStalk with a load balancer, the load balancer has installed a SSL Certificate, and the connection between the load balancer and the EC2 instances are in ports 80. Maybe it could be helpful.
The Elmah log:
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary2 headers, String key, String[] values)
at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware1.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Mapping.MapMiddleware.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thanks!!
have you tried with removing app.Context.Response.Headers.Remove("Server"); i think there is this is the issue?

Categories