【问题标题】:Flutter web call to .net core api error 'Access-Control-Allow-Origin'Flutter web 调用.net core api 错误'Access-Control-Allow-Origin'
【发布时间】:2021-01-07 07:13:05
【问题描述】:

对 .net core api 的 Flutter Web 调用错误“Access-Control-Allow-Origin”

帮帮我我要flutter-Web call api

我使用.net core api

如何在 .net core api 上允许“Access-Control-Allow-Origin”

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.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

【问题讨论】:

    标签: flutter asp.net-core


    【解决方案1】:

    该错误表示您的 api(这与颤振无关)由于 CORS 策略而阻止了请求。 CORS 阻止来自其他 IP 的请求。所以你几乎必须启用它。

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

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

    【讨论】:

    • 如何为颤振启用特定来源?
    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2019-03-21
    • 2017-12-17
    • 2014-12-25
    • 2016-12-09
    • 2018-12-12
    相关资源
    最近更新 更多