I have a Blazor (ASP.Net Core) application that runs on Azure app service.
I have a working solution with MSAL fetching and caching tokens on my local machine.
When publishing to Azure app service I get an access denied error when using http://localhost as redirectURL
HttpListenerException: Access is denied.
System.Net.HttpListener.SetupV2Config()
It seems like MSAL cant find an open port for the communication. How can I solve this problem?
Here is the C# code producing the error
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(appClientId)
.WithRedirectUri(redirectUrl)
.Build();
TokenCacheHelper.EnableSerialization(app.UserTokenCache);
var accounts = await app.GetAccountsAsync();
IAccount firstAccount = accounts.FirstOrDefault();
try
{
authResult = await app.AcquireTokenSilent(scopesList, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException)
{
try
{
>---------- THIS IS WHERE IT FAILS ---------------<
authResult = await app.AcquireTokenInteractive(scopesList)
.ExecuteAsync();
}
catch (Exception ex)
{
logger.LogError("GetTokenPublic() Error acquiring Token {ex}", ex);
return false;
}
}
catch (Exception ex)
{
logger.LogDebug("GetTokenPublic() Error acquiring token silently {ex}", ex);
return false;
}
Input is
scopes = "openid offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/Calendars.Read https://graph.microsoft.com/Calendars.Read.Shared"
redirectURL = "http://localhost"
Full error code
System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, Func`2 responseProducer, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.InterceptAuthorizationUriAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)
at MinServiceAssistent.Data.GraphService.GetTokenPublic() in C:\Michael\blazor_repository\MinServiceAssistent\Data\GraphService.cs:line 182
at MinServiceAssistent.Data.GraphService.Initialize(String userId) in C:\Michael\blazor_repository\MinServiceAssistent\Data\GraphService.cs:line 61
at MinServiceAssistent.Areas.Identity.Pages.Account.Manage.OutlookIntegrationModel.OnPostConnectToAzureAsync() in C:\Michael\blazor_repository\MinServiceAssistent\Areas\Identity\Pages\Account\Manage\OutlookIntegration.cshtml.cs:line 80
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
UPDATE - SOLVED/RE-IMPLEMENTED
I've solved the issue by using a ConfidentialClientApplication in stead of a PublicApplication. The only thing I had to change was to fetch the authorization code manually using:
string url =
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?" +
"client_id=" + appClientId +
"&response_type=code" +
"&redirect_uri=" + redirectUrl +
"&response_mode=query" +
"&scope=" + appScopes +
"&state=12345";
When receiving the authorization code I use AcquireTokenByAuthorizationCode and store the token in my TokenCache and voila :-)
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(appClientId)
.WithRedirectUri(redirectUrl)
.WithClientSecret(appClientSecret) // or .WithCertificate(certificate)
.WithLogging(Log, Microsoft.Identity.Client.LogLevel.Info, true)
.Build();
TokenCacheHelper.EnableSerialization(app.UserTokenCache);
authResult = await app.AcquireTokenByAuthorizationCode(scopesList, authorizationCode).ExecuteAsync();
Solution was to re-implement. See description in original post.
Related
I am devlopping a web site with Blazor Server Side. I'm using Openiddict for openid authentication. When i make a signout :
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
i have an error :
2022-04-06T15:32:40.8217702+02:00 [ERR] (Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware) An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly()
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set_Item(String key, StringValues value)
at Microsoft.AspNetCore.Http.IHeaderDictionary.set_ContentType(StringValues value)
at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_ContentType(String value)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.InvokeCore(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
2022-04-06T15:32:40.8425233+02:00 [WRN] (Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware) The response has already started, the error handler will not be executed.
2022-04-06T15:32:40.8468997+02:00 [ERR] (Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer) Connection ID ""18086456104325218332"", Request ID ""4000001d-0000-fb00-b63f-84710c7967bb"": An unhandled exception was thrown by the application.
Precision: the website is hosted on iis and i don't have error in debug with kestrel...
Could you help me?
My service is working perfectly locally however when I deploy it on Azure as a Windows .net core 5 Free App service, It throws following exception. My code is shown below.
What is the reason for this? Do I have to install any additional components?
var bf = new BrowserFetcher();
await bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var options = new LaunchOptions
{
Headless = true,
ExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultChromiumRevision)
};
List<NewsItem> newsItems = new List<NewsItem>();
using (var browser = await Puppeteer.LaunchAsync(options)) **<= exception thrown here**
using (var page = await browser.NewPageAsync())
{
await page.GoToAsync(url);
Exception:
System.ComponentModel.Win32Exception (14001): The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at PuppeteerSharp.States.ChromiumStartingState.StartCoreAsync(LauncherBase p) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\States\ChromiumStartingState.cs:line 68
at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\Launcher.cs:line 63
at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in C:\projects\puppeteer-sharp\lib\PuppeteerSharp\Launcher.cs:line 86
at NewsAnalyzer.AsxNewsManager.GetNewsItems() in C:\Users\t\source\repos\NewsAnalyzer\NewsAnalyzer\NewsManager.cs:line 24
at NewsApi.Controllers.NewsController.Post() in C:\Users\t\source\repos\NewsAnalyzer\NewsApi\Controllers\NewsController.cs:line 44
at lambda_method5(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
I have asp.net core API running on docker container the container is running on Linux machine. I use FirebaseAdmin to push notifications to Firebase. If I run the container on my local windows machine it works fine. But if I deploy it to the linux maching I am getting 'FirebaseAdmin.Messaging.FirebaseMessagingException: Unknown error while making a remote service call: The SSL connection could not be established'
Code:
public async Task<BatchResponse> SendNotification(List<string> registrationTokens, PushMessage pushMessage)
{
FirebaseApp defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "notificationsKey.json"))
});
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
var message = new MulticastMessage()
{
Tokens = registrationTokens,
Data = pushMessage.Data,
Notification = pushMessage.Notification,
};
BatchResponse response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
return response;
}
I am getting this error
FirebaseAdmin.Messaging.FirebaseMessagingException: Unknown error while making a remote service call: The SSL connection could not be established, see inner exception.
---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.
---> System.Net.Sockets.SocketException (104): Connection reset by peer
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request)
at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)
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.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Google.Apis.Http.ConfigurableMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Google.Apis.Requests.BatchRequest.ExecuteAsync(CancellationToken cancellationToken)
at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendBatchRequestAsync(IEnumerable`1 messages, Boolean dryRun, CancellationToken cancellationToken)
at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendAllAsync(IEnumerable`1 messages, Boolean dryRun, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at FirebaseAdmin.Messaging.FirebaseMessagingClient.SendAllAsync(IEnumerable`1 messages, Boolean dryRun, CancellationToken cancellationToken)
at FirebaseAdmin.Messaging.FirebaseMessaging.SendAllAsync(IEnumerable`1 messages, Boolean dryRun, CancellationToken cancellationToken)
at FirebaseAdmin.Messaging.FirebaseMessaging.SendMulticastAsync(MulticastMessage message, Boolean dryRun, CancellationToken cancellationToken)
at FirebaseAdmin.Messaging.FirebaseMessaging.SendMulticastAsync(MulticastMessage message, Boolean dryRun)
at FirebaseAdmin.Messaging.FirebaseMessaging.SendMulticastAsync(MulticastMessage message)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I am creating a Blazor Server app and Implemented Authentication using Identity Server.
Everything was working fine until I published it to Azure. Everything is working except Login & Register which return
"Sorry, there's nothing at this address."
When I click Login Azure log stream shows this exception
An unhandled exception has occurred while executing the request.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelActivatorProvider.<>c__DisplayClass1_0.<CreateActivator>b__0(PageContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.<>c__DisplayClass3_0.<CreateModelFactory>b__0(PageContext pageContext)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.CreateInstance()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and Register:
An unhandled exception has occurred while executing the request.
System.Security.SecurityException: Invalid assembly public key. (0x8013141E)
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
at System.Reflection.RuntimePropertyInfo.get_Signature()
at System.Reflection.RuntimePropertyInfo.get_PropertyType()
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.CreateModel(PageActionDescriptor actionDescriptor, TypeInfo pageTypeInfo)
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.OnProvidersExecuting(PageApplicationModelProviderContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageLoader.LoadAsyncCore(PageActionDescriptor actionDescriptor)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageLoaderMatcherPolicy.ApplyAsyncAwaited(CandidateSet candidates, Task`1 actionDescriptorTask, Int32 index)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.SelectEndpointWithPoliciesAsync(HttpContext httpContext, IEndpointSelectorPolicy[] policies, CandidateSet candidateSet)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatch|8_1(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matchTask)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and my startup page is:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDisplayMessage, DisplayMessage>();
services.AddServices();
services.AddScoped<IAuthenticationStateService, AuthenticationStateServiceServerSide>();
services.AddAuthentication();
services.AddDbContextPool<MainDbContext>(options => options
.UseLoggerFactory(MyLoggerFactory)
.EnableSensitiveDataLogging()
.UseMySql(Configuration.GetConnectionString(db), mySqlOptions => mySqlOptions
.ServerVersion(new Version(8, 0, 19), ServerType.MySql)));
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
})
.AddSignInManager<ApplicationSignInManager>()
.AddEntityFrameworkStores<MainDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
var assemlies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(a => a.FullName.StartsWith("LaWeb")).Select((item) => Assembly.Load(item)).ToList();
assemlies.Add(Assembly.GetExecutingAssembly());
services.AddAutoMapper(assemlies);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
It works perfectly when runnning from visual studio or when publishing localy to a folder and then running using cmd...
We are using an Azure function to send push notifications via Azure NotificationHubClient. This function is called a lot at peak times on live environment and as a result we got a lot of SocketExceptions thrown from the NotificationHubClient.SendNotificationAsync() method.
Exception details:
Microsoft.Azure.NotificationHubs.Messaging.MessagingException: Unexpected exception encountered TimeStamp:2020-03-27T04:14:35.4655705Z ---> System.Net.Http.HttpRequestException: Cannot assign requested address ---> System.Net.Sockets.SocketException: Cannot assign requested address
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Microsoft.Azure.NotificationHubs.NotificationHubClient.SendRequestAsync(HttpRequestMessage request, String trackingId, HttpStatusCode[] successfulResponseStatuses, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Azure.NotificationHubs.ExceptionsUtility.HandleUnexpectedException(Exception ex, String trackingId)
at Microsoft.Azure.NotificationHubs.ExceptionsUtility.TranslateToMessagingException(Exception ex, Int32 timeoutInMilliseconds, String trackingId)
at Microsoft.Azure.NotificationHubs.NotificationHubClient.SendRequestAsync(HttpRequestMessage request, String trackingId, HttpStatusCode[] successfulResponseStatuses, CancellationToken cancellationToken)
at Microsoft.Azure.NotificationHubs.NotificationHubClient.SendNotificationImplAsync(Notification notification, String tagExpression, String deviceHandle, CancellationToken cancellationToken)
We create the NotificationHubClient like:
new NotificationHubClient(connectionString, hubName, new NotificationHubClientSettings
{
OperationTimeout = TimeSpan.FromSeconds(10)
});
I've observed that the Microsoft implementation behind is instantiating a new HttpClient on each new NotificationHubClient instantiation - which would probably be the problem(the well known socket exhaustion), but I have no ideea how this could be tackled.
Has anyone confronted with the same problem and managed to fix it some way? Thanks
In the end we managed to overcome the problem by injecting
IHttpMessageHandlerFactory _httpMessageHandlerFactory;
in our class and pass it to the notificationHubClient in the constructor:
return new NotificationHubClient(connectionString, hubName,
new NotificationHubClientSettings
{
OperationTimeout = TimeSpan.FromSeconds(10),
MessageHandler = _httpMessageHandlerFactory.CreateHandler()
});
There is a RESTful API for Notification Hubs. You can see it here. If you wanted more control, you could write your own wrapper around the methods you need, making sure to set the HttpClient instance as a static member variable within your Azure Function.