我正在使用angualr 6将Signlar与Web api2集成。以下是我的文件:
Startup.cs(API)
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/NotificationHub", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true
};
map.RunSignalR(hubConfiguration);
});
HubClient
public interface NotificationHubClient
{
Task BroadcastMessage(string type, string payload);
}
NotificationHub
public class NotificationHub : Hub<NotificationHubClient>
{
public void Hello()
{
Clients.All.BroadcastMessage("alert", "1");
}
}
SignalRService(角度6)
import { Injectable } from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { appConfig } from '../app.config';
@Injectable()
export class SignalRService {
public notificationHubUrl = `${appConfig.ApiProjectUrl}NotificationHub`;
private hubConnection: signalR.HubConnection
public startConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(this.notificationHubUrl)
.build();
this.hubConnection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err))
}
}
在控制台窗口上出现以下错误:
Access to XMLHttpRequest at 'https://localhost/Project.API/api/NotificationHub/negotiate' from origin 'http://localhost:4301' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.