当我运行有角度的应用程序时,我得到了一个CORS,尽管我已经在.NET核心应用程序中启用了它,但是常规的HTTP请求似乎可以正常工作,而SignalR只是问题所在。任何建议将不胜感激。预先感谢。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/chat/negotiate. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/chat/negotiate. (Reason: CORS request did not succeed).
[2019-07-06T19:34:25.061Z] Warning: Error from HTTP request. 0: . Utils.js:206
[2019-07-06T19:34:25.065Z] Error: Failed to complete negotiation with the server: Error Utils.js:203
[2019-07-06T19:34:25.070Z] Error: Failed to start the connection: Error Utils.js:203
Error while establishing connection :( chatComponent.component.ts:43:28
这是我的Startup.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
// using WebApiServerApp.Searching;
namespace WebApiServerApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:4200");
}));1
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseMvc();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/api/chat");
});
}
}
}
这是我的ChatHub类
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.SignalR;
namespace WebApiServerApp
{
public class ChatHub : Hub
{
public Task SendToAll(string name, string message)
{
return Clients.All.SendAsync("ReceiveMessage", name, message);
}
}
}
这是我的忠实客户
import { Component, OnInit } from '@angular/core';
import { ITag } from '../Tag/tag';
import { TagComponent } from '../Tag/tag.component';
import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { IMessage } from './Message';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
@Component({
selector:'chat',
templateUrl:"./chatComponent.component.html",
//styleUrls: ['./tagSearch.component.css']
// providers: [ ChatService ]
})
export class ChatComponent implements OnInit {
hubConnection: HubConnection;
message: string;
nick: string;
messages: string[] = [];
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.nick = window.prompt('Your name:', 'John');
//http://localhost:5001/api/chat
this.hubConnection = new HubConnectionBuilder().withUrl("http://localhost:5000/api/chat", {
skipNegotiation: true,
transport: HttpTransportType.WebSockets
}).build();
this.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this.hubConnection.on('ReceiveMessage', (nick: string, receivedMessage: string) => {
const text = `${nick}: ${receivedMessage}`;
this.messages.push(text);
});
}
public sendMessage(): void {
this.hubConnection
.invoke('SendToAll', this.nick, this.message)
.catch(err => console.error(err));
}
}
更新,新错误:
Firefox can’t establish a connection to the server at ws://localhost:5000/api/chat. WebSocketTransport.js:85
[2019-07-06T20:06:31.730Z] Error: Failed to start the connection: null Utils.js:203
Error while establishing connection :(
在Chrome中显示
WebSocketTransport.js:85 WebSocket connection to 'ws://localhost:5000/api/chat' failed: Error during WebSocket handshake: Unexpected response code: 307
(anonymous) @ WebSocketTransport.js:85
Utils.js:203 [2019-07-06T20:31:51.740Z] Error: Failed to start the connection: null
push../node_modules/@aspnet/signalr/dist/esm/Utils.js.ConsoleLogger.log @ Utils.js:203
chatComponent.component.ts:46 Error while establishing connection :(
答案 0 :(得分:2)
尝试从 Startup.cs 中删除app.UseHttpsRedirection();
。
代码307是重定向响应。因此,这可能就是问题所在。
或者,或者查看有关对所有内容使用HTTPS的信息。