我的ASP.NET核心API和Angular Client有问题。我想实现SignalR在API和Angular之间建立连接。cors策略已在我们的客户端和API上激活,因为我们已经可以使用我们的客户端从API检索数据。但是现在的问题是,当我尝试使用SignalR时,收到CORS POLICY错误:
通过CORS策略已阻止从源“ http:// localhost:4200 ” 访问“ http:// localhost:50501 / CoordinatorHub / negotiate ” 处的XMLHttpRequest :对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin'标头出现在请求的资源上。
但是我们的API上的Startup.cs内部已经有cors政策,就像这样:
在ConfigureServices方法中:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
builder.WithOrigins("http://localhost:4200/")
.AllowCredentials()
//.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowedToAllowWildcardSubdomains());
});
Run Code Online (Sandbox Code Playgroud)
在Configure方法中:
app.UseCors("AllowSpecificOrigin");
Run Code Online (Sandbox Code Playgroud)
在我们的客户端中,我们只想尝试在API和客户端之间建立连接,就像这样:
this.hubConnection.start({withCredentials: false}).then(() =>
this.hubConnection.invoke('send', 'Hello'));
Run Code Online (Sandbox Code Playgroud) 当我尝试在SignalR中使用组时,我有些奇怪。我为我的集线器做了一堂课,在对所有客户端执行ping操作时,其中的Task起作用。我已经完成了两种方法,一种是添加,另一种是从组中删除客户端。但是,当我尝试在一个组中建立一个客户时,还没有完成任何事情。这是中心的代码:
public interface IActionClient
{
// User is in front of the cameras
Task HighlightUser(Guid userId);
// When users added or deleted
Task UpdateGame(int gameId);
Task JoinGroupAsync(string groupName);
Task LeaveGroupAsync(string groupName);
}
// possible clients
public enum ClientType
{
Leaderboard,
Dashboard,
Register
}
public class OneHub : Hub<IActionClient>
{
public OneHub()
{
}
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public async Task JoinGroupAsync(string groupName) => await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
public async Task LeaveGroupAsync(string groupName) => await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName); …
Run Code Online (Sandbox Code Playgroud) 我在Angular中遇到一个库问题。我已经完成了一个库,在其中我用HttpClient询问API,但是当我尝试从该库GameService继续上一个类时,出现了一个问题,我收到:“错误静态注入器:StaticInjectorError(AppModule)[GameService-> HttpClient]” 。当我看到该消息时,我尝试将HttpModule导入我的应用程序中并添加提供程序HttpClient,但未进行任何更改。这是我的类库的代码:
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Game } from './model/game';
import { Observable } from 'rxjs';
import { EndPointGetterService } from '../utilities/end-point-getter.service';
@Injectable({
providedIn: 'root'
})
export class GameService {
private gameUrl = localStorage.getItem('endpoint') + '/Games';
private headers: HttpHeaders;
constructor(private http: HttpClient, private EPGetter: EndPointGetterService) {
this.headers = new HttpHeaders({
'Access-Control-Allow-Origin': 'http://localhost:4200',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': '*',
});
}
getStateGame(groupName: string): Observable<number> {
return this.http.get<number>(this.EPGetter.getEndPointUrl() + '/Games/' + groupName …
Run Code Online (Sandbox Code Playgroud)