【发布时间】:2021-09-26 15:11:32
【问题描述】:
我有一个带有 asp.net core 的 web api 和一个 Asp.Net core webapp,它们之间没有发生通信。
我使用 Postman 进行了 api 测试,一切正常,但是当它是 web 应用程序时,会返回此错误: 从源“http://localhost:39903”访问“http://localhost:15741/api/Home/CalculaEmprestimo”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我在 web api 上配置了 CORS,但错误仍然存在。
API
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:39903");
});
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
}
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
角度服务
import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmprestimo } from '../Model/emprestimo.interface';
import { IEmprestimoResult } from '../Model/emprestimoresult.interface';
import { fromEvent, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { strict } from 'assert';
@Injectable({
providedIn: 'root'
})
export class EmprestimoService {
constructor(private http: HttpClient) { }
postEmprestimo(pEmprestimo: IEmprestimo): Observable<IEmprestimoResult>
{
const headers = { 'Content-Type': 'application/json', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Connection':'keep-alive' };
const body = {
"parcelas": pEmprestimo.parcelas,
"valorParcelas": pEmprestimo.valorParcelas,
"valorEmprestimo": ""
};
var result = this.http.post<IEmprestimoResult>('http://localhost:15741/api/Home/CalculaEmprestimo', body);
return result;
}
}
谁能帮我解决这个问题?
【问题讨论】:
-
如果您尝试在 ConfigureServices 中写入 localhost:39903 而没有尾部斜杠 - 这有什么不同吗?
-
我把最后的斜线去掉了,但还是一样。
标签: c# asp.net angular asp.net-web-api