繁体   English   中英

angular 和 asp.net 内核 3.1 cors 策略

[英]angular and asp.net core 3.1 cors policy

我正在尝试将我的 angular 前端连接到我的 ASP.Net core 3.1 ef 后端,但遇到了 CORS 策略问题。 我已经尝试了我在这个网站上可以找到的所有东西,但没有运气,我不确定我错过了什么。 我根据我在其他帖子中发现的内容调整了我的一些代码能够将 CORS 错误更改为 400 错误请求错误,下面是我的 startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using backend.Context;
using backend.Middleware;
using backend.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace backend
{
    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.AddCors(options =>
         {
             options.AddPolicy(MyAllowSpecificOrigins, builder =>
             {

                 builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();



             });
         });




            services.AddDbContext<NineToFiveContext>(opt => opt.UseSqlServer
            (Configuration.GetConnectionString("SqlConnection")));


            services.AddControllers().AddNewtonsoftJson(s =>
            {
                s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddScoped<IUserRepo, SqlUserRepo>();

            services.AddScoped<IJobRepo, SqlJobRepo>();

            services.AddScoped<IFaqRepo, SqlFaqRepo>();


        }

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




            app.UseRouting();

            app.UseMiddleware<CorsMiddleware>();


            app.UseCors(MyAllowSpecificOrigins);


            app.UseAuthorization();

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

我尝试根据此站点上的类似帖子添加一些中间件,但它也不起作用,这是中间件

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace backend.Middleware
{
    public class CorsMiddleware
    {
        private readonly RequestDelegate _next;
        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            await _next(context);
        }
    }
}

最后一篇帖子说问题出在他的连接字符串上,我的在下面。 我认为没关系,但不是 100% 肯定,因为我只是在实习。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SQLConnection": "Server=xxx; Database=9ineTo5iveDB; Trusted_Connection=True"
  }
}

任何帮助将不胜感激。 根据微软文档,我尝试在三个不同级别使用 cors 政策,但没有一个有效。

尝试在 builder.WithOrigins 中添加 http://localhost:4200

app.UseCors(builder => builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM