Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I deployed my new bilingual ASP.NET Core website as Azure WebApp.
Currently i'm getting from time to time:
{"An item with the same key has already been added. Key: Content-Language"} at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException[T](T key)
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.Add(String key, StringValues value)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<invoke>d__5.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.<invoke>d__6.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<invoke>d__6.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at MannsBlog.Services.EmailExceptionMiddleware.<invoke>d__5.MoveNext() in C:\Users\Sasch\source\repos\saschamannsde\src\MannsBlog\Services\EmailExceptionMiddleware.cs:line 47


The mentioned EmailExceptionMiddleware does:

C#
public class EmailExceptionMiddleware
   {
       private readonly RequestDelegate _next;
       private readonly IMailService _mailService;
       private readonly IHostEnvironment _env;
       private ILogger<EmailExceptionMiddleware> _logger;

       public EmailExceptionMiddleware(RequestDelegate next, IMailService mailService, IHostEnvironment env, ILogger<EmailExceptionMiddleware> logger)
       {
           _next = next;
           _mailService = mailService;
           _env = env;
           _logger = logger;
       }

       public async Task Invoke(HttpContext context)
       {
           try
           {
               await _next.Invoke(context);  <-- Line 47
           }
           catch (Exception ex)
           {
               await _mailService.SendMailAsync("exceptionMessage.txt", "Sascha Manns", "Sascha.Manns@outlook.de", "[MannsBlog Exception]", ex.ToString());

               // Don't swallow the exception
               throw;
           }

       }


I used in Startup/ConfigureServices:

C#
svcs.Configure<RequestLocalizationOptions>(options =>
            {
                List<CultureInfo> supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE")
                };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                options.ApplyCurrentCultureToResponseHeaders = true;
            });


And by Startup/Configure:

C#
// Globalizing & Localizing
            var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>()?.Value;
            app.UseRequestLocalization(options);

            app.UseEndpoints(cfg =>
            {
                cfg.MapControllers();
                cfg.MapHealthChecks("/_hc");
                cfg.MapHealthChecks("/_hc.json", new HealthCheckOptions()
                {
                    Predicate = _ => true,
                    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
                });
                cfg.MapBlazorHub();
            });


What I have tried:

I don't know from where the exception will be written. I already have done a Remote-Debugging and saw in the "context" range, a Content-Language is placed grouped in the Response-Header or Body. Maybe this is mean't? And how to fix it?
Posted
Updated 7-Dec-21 10:53am
v3
Comments
Richard Deeming 6-Dec-22 4:34am    
Not sure if you're still looking for an answer to this, but the stack trace says the error occurred in the RequestLocalizationMiddleware.

It looks like this may have been fixed in .NET 6:
An item with the same key has already been added. Key: Content-Language when using UseRequestLocalization and UseStatusCodePagesWithReExecute · Issue #36105 · dotnet/aspnetcore · GitHub[^]

Last line of the error message states:
C:\Users\Sasch\source\repos\saschamannsde\src\MannsBlog\Services\EmailExceptionMiddleware.cs:line 47


The error occurred on Line 47 of EmailExceptionMiddleware.cs.

However, that line is not shown in your sample code. Take a close look at that line.
It'll probably give you a better idea of what is happening.
 
Share this answer
 
Comments
Sascha Manns 7-Dec-21 16:52pm    
Sorry, forgotten that line numbers aren't included by the snippings.

The line 47 just does:

await _next.Invoke(context);
raddevus 7-Dec-21 17:21pm    
Have you tried it without the code that is in the catch{}?
Remove the async call from the catch and try it again.
I believe the error is occurring because it's attempting to add the same module more than once. and that is possibly happening because it throws an exception and calls the async call.
Also, try debugging / stepping over each line and see what happens.
If you used same name in model than this conflict has to be come.
Example: - if you used SupplierType and suppliertype in same model than it shows an error like that An item with the same key has already been added .

Sujata Maurya reply on 06-12-2022
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900