为ASP.NET core 2.0 web api启用CORS [英] Enable CORS for ASP.NET core 2.0 web api
本文介绍了为ASP.NET core 2.0 web api启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用ASP.Net Core 2.0创建了一个Web API,其中我实现了启用CORS的代码,如下所示:
I've created a Web API using ASP.Net Core 2.0 wherein I've implemented code for enabling CORS as given below:
// 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("AllowFromAll",
builder => builder
.WithMethods("GET", "POST")
.AllowAnyOrigin()
.AllowAnyHeader());
}); ;
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowFromAll");
app.UseMvc();
}
}
}
通过fiddler调用它来验证响应时,我得到http 401:UnAuthorized错误。
我不确定如果我错过了一些启用CORS的实现。
有什么建议吗?
我尝试过:
When verified for the response by calling it through fiddler, I get http 401: UnAuthorized error.
I'm not sure If I missed some implementation to enable CORS.
Any suggestions please?
What I have tried:
// 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("AllowFromAll",
builder => builder
.WithMethods("GET", "POST")
.AllowAnyOrigin()
.AllowAnyHeader());
}); ;
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowFromAll");
app.UseMvc();
}
}
}
推荐答案
朋友请参考此网址,我相信你可以如果没有找到你的答案然后只是让我知道我会解决它:在ASP.NET Web API 2中启用跨源请求Microsoft Docs [ ^ ]
步骤1-
Hi friend refer this url and i am sure you can find your answer if not then just do let me know i will fix it : Enabling Cross-Origin Requests in ASP.NET Web API 2 | Microsoft Docs[^]
Step 1-
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
步骤2 -
Step 2-
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "yourclientApplicationRootURL", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
这篇关于为ASP.NET core 2.0 web api启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文