![](/img/trans.png)
[英]Getting the CORS error while connecting the signalR hub in angular with asp net core from server
[英]Error trying to connect to asp.net core signalr hub from Angular App
我有一個 asp.net 核心 3.1 應用程序,它使用 Microsoft.AspNetCore.SignalR 1.1.0 和 Microsoft.883587760644488.SignalR
在啟動信號中設置如下
services.AddSignalR().AddAzureSignalR("Endpoint=https://xxxxx.service.signalr.net;AccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=;Version=1.0;");
...
app.UseAzureSignalR(routes =>
{
routes.MapHub<TransactionHUB>("/updateAll");
});
在 angular 應用程序中安裝
npm 安裝@as.net/signalr
我開始這樣連接
public startConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:44391/updateAll')
.build();
this.hubConnection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err));
}
加載應用程序時出現錯誤。
錯誤:無法啟動連接:錯誤:服務器不支持客戶端支持的任何傳輸。
更新
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoWrapper;
using Entities;
using Infrastructure;
using Infrastructure.Contracts;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OData;
using Microsoft.OData.Edm;
using Services;
using Services.Contracts;
namespace BBBankApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// services.AddCors(options =>
// {
// options.AddPolicy(MyAllowSpecificOrigins,
// //builder =>
// //{
// // builder.WithOrigins("http://localhost:4200");
// //});
// builder => builder.AllowAnyOrigin()
//.AllowAnyMethod()
//.AllowAnyHeader());
// });
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
//services.Configure<ApiBehaviorOptions>(options =>
//{
// options.SuppressModelStateInvalidFilter = true;
//});// stopping default asp.net core model state validation
services.AddControllers(config =>
{
config.Filters.Add(new ModelValidationCheckFilter());
});
services.AddScoped<ITransactionService, TransactionService>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<DbContext, BBBankContext>();
services.AddScoped<ITransactionRepository, TransactionRepository>();
services.AddScoped(typeof(IRepository<>), typeof(SQLServerRepository<>));
services.AddScoped<IAccountService, AccountService>();
var connection = @"Server=(localdb)\mssqllocaldb;Database=xxxxx;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BBBankContext>(
b => b.UseSqlServer(connection)
.UseLazyLoadingProxies(false) //Install-Package Microsoft.EntityFrameworkCore.Proxies -Version 3.1.1
//Lazy Loading means that the navigation properties will be loaded automatically as soon as they are called
//if true the odata expand will work on Transactions as well.
);
services.AddOData();
services.AddODataQueryFilter();
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
}).AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddSignalR().AddAzureSignalR("Endpoint=https://xxxxxx.service.signalr.net;AccessKey=xxxxxxxxxxxx+9xdFN63uV8mPjIakR2ZWoJhmTk=;Version=1.0;");
}
// 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.UseApiResponseAndExceptionWrapper(new AutoWrapperOptions { ShowStatusCode = true, UseApiProblemDetailsException = true, IsDebug = true, EnableExceptionLogging = true, LogRequestDataOnException = true }); //
// app.UseCustomExceptionMiddleware();
// was using this middleware only for logging. but do we really need it if Autowrapper has its own middleware
// that logs using default logging configuration of asp.net core.
app.UseCustomLogginMiddleware();
// app.UseCors(MyAllowSpecificOrigins);
app.UseCors("CorsPolicy");
app.UseMvc(b =>
{
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseAzureSignalR(routes =>
{
routes.MapHub<TransactionHUB>("/updateAll");
});
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();
builder.EntitySet<Account>("Accounts").EntityType.Count().Page(50, 3).Expand().Filter().Select().OrderBy();
builder.EntitySet<User>("Users");
builder.EntitySet<Transaction>("Transactions");
return builder.GetEdmModel();
}
}
}
更新 2
我也嘗試過不同版本的微軟信號,但都給我同樣的錯誤。 安裝在服務器端的包是最近安裝的“*** Common”只是為了檢查。 不確定是否需要。
更新 2我刪除了 Azure Signalr 並僅在服務器端使用 Microsoft.AspNetCore.SignalR 1.1.0,在客戶端使用 @microsoft/signalr@latest。 但它是同樣的錯誤。
首先,不要使用@as.net/signalr
因為它已經過時了。 正確的 package 是@microsoft/signalr
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.