Tah*_*bal 2 api cors asp.net-core-mvc asp.net-core angular
我在 MVC Core 中创建了一个 API 项目。在我的控制器中,我添加了一些与 Postman 完美配合的 GET 和 POST 方法的 API。但是当我尝试从我的 Angular 应用程序调用它们时,它们给了我 CORS 错误:
从源访问 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
我用谷歌搜索解决方案,发现我需要添加 CORS NuGet 包。我这样做了,但错误仍然存在。
以下是我的Startup.cs文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using webapp1.Model;
namespace webapp1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddDbContext<TodoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors(options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我的API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using webapp1.Model;
namespace webapp1.Controllers
{
[ApiController]
[Route("[controller]")]
public class TodoController : ControllerBase
{
TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
}
[HttpGet]
public List<Todo> Get()
{
return _context.Todos.ToList();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要在 Web Api 中启用 CORS。全局启用 CORS 的更简单和首选的方法是将以下内容添加到 web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
更新:
在 ASP.Net 核心中,我们没有 web.config,而是有 app.config 文件。你仍然需要有 web.config 你可以添加一个 Web 配置项模板。您可以使用它,例如更改最大文件上传限制等。
web.config 文件在您发布项目时生成。
| 归档时间: |
|
| 查看次数: |
7768 次 |
| 最近记录: |