首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flutter web调用.net核心应用程序接口错误‘访问-控制-允许-原点’

Flutter web调用.net核心应用程序接口错误‘访问-控制-允许-原点’
EN

Stack Overflow用户
提问于 2020-09-21 15:45:26
回答 1查看 489关注 0票数 0

Flutter web调用.net核心应用程序接口错误‘访问-控制-允许-原点’

帮助我,我想要flutter-Web调用api

我使用.net核心应用编程接口

如何在.net核心接口上允许‘访问-控制-允许-起源’

Startup.cs中的代码

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace test_api
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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();
        }

        // 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.UseRouting();

            app.UseCors(MyAllowSpecificOrigins);

            // app.UseResponseCaching();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Flutter Web error

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-21 16:06:22

该错误表示您的api (与flutter无关)由于CORS策略而阻止了该请求。CORS会屏蔽其他IP的请求。因此,您几乎必须启用它。

代码语言:javascript
复制
services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin() 
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
    });

遵循指南和答案here。尝试搜索您的特定asp.net核心版本。此外,控制器顶部的EnableCors属性是工作所必需的。您的“仅允许特定来源”根本不指定任何类型的主机。它只指定策略的名称,而且您还没有在services中使用过

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63988074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档