在 .net core2.2.0 上使用 nugetPackage:
我正在使用 angular 连接 signalr:
package.json: "@aspnet/signalr": "1.1.0",
我的 angular 前端代码:
import { Component } from '@angular/core';
import * as signalR from "@aspnet/signalr";
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor() { }
private _hubConnection: signalR.HubConnection;
msgs: Message[] = [];
ngOnInit(): void {
this._hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:44390/chatHub')
.build();
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
this.msgs.push({ Type: type, Payload: payload });
});
}
}
export class Message {
public Type: string
public Payload: string
} .catch(err => console.log('Error while establishing connection :('));
this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
this.msgs.push({ Type: type, Payload: payload });
});
}
}
export class Message {
public Type: string
public Payload: string
}
我的中心类:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SharAPI.Models
{
public class ChatHub : Hub
{
public async Task BroadcastMessage(string msg)
{
await this.Clients.All.SendAsync("BroadcastMessage", msg);
}
}
}
startup.cs(ConfigureServices):
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// other codes
}
startup.cs(配置):
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseHttpsRedirection();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseMvc();
//other codes
}
控制器:
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SharAPI.Models;
using System;
namespace SharAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class MessageController : ControllerBase
{
private ChatHub _hub;
public MessageController(ChatHub hub)
{
_hub = hub ;
}
[HttpPost]
public string Post([FromBody]Message msg)
{
string retMessage = string.Empty;
try
{
_hub. BroadcastMessage(msg.message);
retMessage = "Success";
}
catch (Exception e)
{
retMessage = e.ToString();
}
return retMessage;
}
}
}
我遇到了以下错误:
由于CORS策略,从源'http://localhost:44390'访问'https://localhost:44390/chatHub/negotiate'的XMLHttpRequest已被阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包括”时,响应中的“Access-Control-Allow-Origin”标头的值不得是通配符“*”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
app.UseCors(options => options.WithOrigins("http://localhost:57122").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
- Ryan