首页 > 解决方案 > 在 web api .net core 上获取类型 cors 的响应

问题描述

我只是想向客户端返回一个 url,我已经完成了 cors 策略的所有配置,但我收到的唯一返回是 cors 类型,没有任何我想要返回的 url 信号,预检请求工作正常,并且请求自己,我的 api 的返回是我的问题。

这是我的startup.cs

 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.AddTransient<ITokenManager, TokenManager>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<IAccountService, AccountService>();
            services.AddSingleton<ITableauService, TableauService>();


            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .Build();

                    });
            });

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
            });

            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)
        {

            app.UseAuthentication();
            app.UseCors("AllowAll");
            app.UseMvc();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
        }
    }

从客户端获取 api 请求

  fetch('https://baseurl?folder=AcompanhamentoComparativoLocaliza&view=DashEmails'
            , {

                headers: new Headers({
                    'authorization': 'AuthToken',
                    'Content-Type':'application/json',

                })
            })
                .then(response => {
                    console.log('teste',response)


                }
                )
                .catch(error => console.error(error))

这是 cors 政策的输出,你们可以看到他们被成功执行

这是我的控制器中的回报

现在我的客户端中的网络

预检网络标头和状态

请求本身

来自 api 的响应

在此先感谢,我希望有任何帮助。

标签: c#asp.net.netasp.net-core-webapi

解决方案


响应类型是cors手段

从有效的跨域请求中收到响应。可以访问某些标题和正文。

所以只需使用以下方式获取返回的数据:

.then(response => {
  response.json().then((data) => {
      console.log(data);
    })
  }
)

另外,如果你想返回url,你应该加上双引号,例如:

return Content("\"https://localhost:8080\"");

推荐阅读