出现此问题的原因可能是由于C#端点的CORS配置问题。CORS允许不同的域和协议进行通信,但需要在服务器端设置。
下面的代码示例演示了如何在ASP.NET Core中启用CORS:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddMvc(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAll");
app.UseMvc();
}
}
在上面的代码中,我们设置了一个名为“AllowAll”的CORS策略,该策略允许任何来源,任何方法和任何标头进行通信。在Configure方法中,我们通过app.UseCors("AllowAll")将CORS中间件添加到管道中。
如果你的C#端点位于不同的域,则还需要在Angular应用程序中启用CORS。可以使用Angular的HttpClient模块中的withCredentials属性实现此目的。在Angular中,我们可以这样做:
import { HttpClient } from '@angular/common/http';
@Injectable() export class MyService { constructor(private http: HttpClient) {}
postData(data: any) {
const url = 'http://example.com/api/endpoint';
return this.http.post(url, data, { withCredentials: true });
}
}
在上面的代码中,我们设置了withCredentials: true,以允许在跨域情况下共享凭据,例如Cookie。