最近用微软官网文档学习ASP.NET Core 创建 Web API时报错,官网学习链接1,官网学习链接2,解决方案如下:
1.在StartUp.cs里Configure方法里介于app.UseRouting()和app.UseEndpoints()添加app.UseCors();
app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
2.在StartUp.cs里ConfigureServices方法里添加services.AddCors();
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddDefaultPolicy( builder => { builder.WithOrigins("*") .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers(); services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); //services.AddSwaggerGen(c => //{ // c.SwaggerDoc("v1", new OpenApiInfo { Title = "TodoItems", Version = "v1" }); //}); }
3.在TodoItemsController.cs添加应用一下默认属性。
参考资料:
https://blog.csdn.net/weixin_30544657/article/details/94884203