我正在尝试在 docker 中部署 signalR 服务器。如果没有 docker,则与本地的测试客户端连接。但现在它显示 Cors 错误并且无法从本地客户端连接
我的程序.cs
using chat_server.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(p => p.AddPolicy("corsPolicy", build =>
{
build.WithOrigins("http://[serverIP]:8100", "https://[serverIP]:8100", "http://[serverIP]:80", "https://[serverIP]:80")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("corsPolicy");
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ChatHub>("/chathub");
app.Run();
我的 Dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 8100
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["chat_server.csproj", "."]
RUN dotnet restore "./chat_server.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "chat_server.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "chat_server.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "chat_server.dll"]
我的演示客户端连接字符串,从本地运行
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://[serverIP]:8100/chathub") // Update with your hub URL
.build();
从控制台我遇到的问题是
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://185.100.232.17:8100/chathub/negotiate?negotiateVersion=1. (Reason: CORS request did not succeed). Status code: (null)
我自己解决了这个问题
更改了 Program.cs ,如
app.UseCors(cp => cp
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
docker运行命令是
docker run -d -p 8100:8100 --name [docker_name] [image_name]