标题: 从蜂窝网络连接到 Blazor SignalR 服务器的超时问题。
描述: 我遇到的问题是,我的 .NET MAUI Android 客户端在蜂窝网络上无法使用公共 IP 地址连接到 Blazor SignalR 服务器。该应用程序使用本地 IP 地址可以正常工作。我已在路由器上尝试过端口转发,但遇到连接超时错误。
客户端代码:
_hubConnection = new HubConnectionBuilder()
.WithUrl("http://MyIpAddress:5011/formhub")
.WithAutomaticReconnect()
.Build();
.// Your server-side code here
// Server side code
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
// Gerald: Enable SignalR functionality
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddSignalR();
builder.Services.AddMudServices();
builder.Services.AddTransient<UpdateFormService>();
builder.Services.AddTransient<ITextService, TextGenerator>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<FormHub>("/formhub");
});
app.Run();
'''
I will appreciate any help
从Android 9(API级别28)开始,Android平台默认不允许明文(HTTP)流量,要求应用程序使用HTTPS来保护数据传输。
因此我们需要设置
usesCleartextTraffic
选项以允许http流量。就像下面这样。
//#if DEBUG
[Application(UsesCleartextTraffic = true)]
//#else
//[Application]
//#endif
public class MainApplication : MauiApplication
{
...
}
你可能会发现我评论了
IF DEBUG
的一些属性,在生产中,使用https
是最好的解决方案,你可以使用[Application(UsesCleartextTraffic = true)]
进行测试。