我有一个我已经设置好的服务器,在生产环境中运行,我们有大量的应用程序调用这个网络服务器。下面的代码是为了演示它允许任何源请求。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
这适用于当前设置的所有服务器。它在我们的内部网络上,内部的其他服务器将使用此服务。
我正在创建一个概念证明,以尝试通过使用 Vue
慢慢地使我们的应用程序现代化。除了这个 axios
请求出错。调用此方法的其他服务器也在使用 .net,但它应该构建相同的请求。
这里是错误。
Failed to load https://{server}/api/application/36626: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
这显然是axios的狂谈。我允许任何来源。我无法想象我们只想使用“简单请求”,所以简单请求的 w3 标准可能不起作用。考虑到这是从服务器返回的 octet-stream
,我认为这可能是一个不正确的错误。代码如下。
<script>
import axios from 'axios'
export default {
name: 'AppList',
data () {
return {
applist: [],
errors: []
}
},
created: function() {
axios.get('https://{server}/api/application/36626')
.then(r => { console.log(response); })
.catch(ex => {
this.errors.push(ex);
})
}
}
</script>
编辑我拥有这台机器的全部权利,我已经确认我可以毫无问题地从我的本地机器使用 Postman GET 请求。
编辑 2 工作 curl 命令 curl -X GET --header 'Accept: application/octet-stream' 'https://{server}/api/Application/36626'
最佳答案
事实证明 .Net Core 服务器设置不正确,直到我尝试在本地计算机上使用浏览器时才出现 CORS
问题。
我不确定 CORS 实现是否发生了变化并且我不知道,或者我是否从一开始就没有做对,但我确定我遵循了指南。
我更改的第一件事是确保在配置应用程序以使用 MVC
之前添加 Cors 策略。
我做的第二件事,我怀疑这是可选的,但最佳实践是,我还将策略逻辑移至 ConfigureServices
方法。
我的最终代码如下所示。我尽量保持机智以维持秩序。
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddOptions();
services.AddSwaggerGen();
///Authentication configuration went here.
services.AddSingleton<IConfiguration>(Configuration);
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, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseSwagger((httpRequest, swaggerDoc) =>
{
swaggerDoc.Host = httpRequest.Host.Value;
});
app.UseSwaggerUi(swaggerUrl: "/{appname}/swagger/v1/swagger.json");
关于asp.net-core - AllowAnyOrigin Cors 不工作 Axios Vuejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47294125/