I have websockets enabled on my iis server. I am using singal R to update a progress bar during downloading. Works and local host but when published to server I get the following.
blazor.web.js:1 [2024-07-08T21:19:28.598Z] Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State.
the full stack trace if needed
blazor.web.js:1 [2024-07-08T21:19:28.598Z] Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.NegotiateAsync(Uri url, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.GetNegotiationResponseAsync(Uri uri, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.SelectAndStartTransport(TransferFormat transferFormat, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsyncCore(TransferFormat transferFormat, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsync(TransferFormat transferFormat, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)
at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken)
at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncInner(CancellationToken cancellationToken)
at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsync(CancellationToken cancellationToken)
at SecureFileShare.Client.Components.ProgressUIComponent.OnInitializedAsync() in C:BHIDEV22WebDevSecureFileShareSecureFileShare.ClientComponentsProgressUIComponent.razor:line 70
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
log @ blazor.web.js:1
blazor.web.js:1 [2024-07-08T21:19:28.599Z] Information: Connection disconnected.
btest/:1 The file at 'http://bhub/btest/api/download' was loaded over an insecure connection. This file should be served over HTTPS.
blazor.web.js:1 Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State.
at Nn.send (blazor.web.js:1:85376)
at gn._sendMessage (blazor.web.js:1:58807)
at gn._sendWithProtocol (blazor.web.js:1:58897)
at gn.send (blazor.web.js:1:59005)
at Fo.beginInvokeDotNetFromJS (blazor.web.js:1:139654)
at y.invokeDotNetMethodAsync (blazor.web.js:1:4322)
at S.invokeMethodAsync (blazor.web.js:1:5830)
at HTMLDivElement.<anonymous> (blazor.bootstrap.js:445:30)
at Object.trigger (event-handler.js:289:15)
at modal.js:196:20
Line 70 is here with startAsync() which is where the connection can’t be started I assume
protected override async Task OnInitializedAsync()
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"), options =>
{
options.UseDefaultCredentials = true;
})
.Build();
_hubConnection.On<int>("ReceiveProgress", p =>
{
progress = p;
InvokeAsync(StateHasChanged);
});
await _hubConnection.StartAsync();
}
here is my program cs
var builder = WebApplication.CreateBuilder(args);
//For windows authentication
//---------------------
//First add nuget package Microsoft.AspNetCore.Authentication.Negotiat
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
//Inject IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
//injects
builder.Services.AddScoped<UserService>();
builder.Services.TryAddEnumerable(
ServiceDescriptor.Scoped<CircuitHandler, UserCircuitHandler>());
//
builder.Services.AddControllers();
//form file upload size
builder.Services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = long.MaxValue; // Set an appropriate limit
});
//Enabling Kestrel Support for the Large Files
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxRequestBodySize = long.MaxValue;
});
//bootstrap
builder.Services.AddBlazorBootstrap();
//Inject repo
builder.Services.AddScoped<ISfsEmailDetailRepo, SfsEmailDetailRepo>();
builder.Services.AddDbContextFactory<SecureFileShareContext>(opt =>
opt.UseSqlServer(builder.Configuration.GetConnectionString("SecureFileShare"))
);
//
//for signalR
builder.Services.AddSignalR();
builder.Services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
["application/octet-stream"]);
});
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
var app = builder.Build();
//for singalR
app.UseResponseCompression();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// 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.UseAuthentication();
app.UseAuthorization();
///
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(SecureFileShare.Client._Imports).Assembly);
app.MapControllers();
//SInglarR
app.MapHub<ChatHub>("/chathub");
app.Run();
my hub
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
function in my download controller for updating my UI. Doubt this is needed but I believe I am missing something in authentication for program.cs. I am not sure why it is not loading as everything I see mentions websockets which are enabled.
private async Task AddFileToArchive(ZipArchive archive, string filePath, string entryName, long totalSize)
{
var entry = archive.CreateEntry(entryName);
using (var entryStream = entry.Open())
using (var fileStream = System.IO.File.OpenRead(filePath))
{
var buffer = new byte[60000];
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await entryStream.WriteAsync(buffer, 0, bytesRead);
bytesWritten += bytesRead;
int percentComplete = (int)((double)bytesWritten / totalSize * 100);
await _hubContext.Clients.All.SendAsync("ReceiveProgress", percentComplete);
}
}
}