Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core .NET 5 API添加访问控制允许源标题-使用Ionic 5.5_Asp.net Core_Ionic Framework_Cors - Fatal编程技术网

Asp.net core .NET 5 API添加访问控制允许源标题-使用Ionic 5.5

Asp.net core .NET 5 API添加访问控制允许源标题-使用Ionic 5.5,asp.net-core,ionic-framework,cors,Asp.net Core,Ionic Framework,Cors,你能帮忙吗,我有一个.NET5WebAPI和Ionic5.5应用程序。我已经将API和Ionic应用程序部署到Azure Web服务。API为Ionic应用程序提供服务,因此它们位于同一个域上-我可以说是同一个源,因为方案和域是相同的 问题是,Ionic应用程序无法调用API,因为它似乎是CORS在阻止它。 在我的API中,我允许任何来源、任何头和凭据,但它仍然不起作用。我已附加了.NET 5 API的Startup.cs文件 启动.cs代码 using AutoMapper; using Ev

你能帮忙吗,我有一个.NET5WebAPI和Ionic5.5应用程序。我已经将API和Ionic应用程序部署到Azure Web服务。API为Ionic应用程序提供服务,因此它们位于同一个域上-我可以说是同一个源,因为方案和域是相同的

问题是,Ionic应用程序无法调用API,因为它似乎是CORS在阻止它。 在我的API中,我允许任何来源、任何头和凭据,但它仍然不起作用。我已附加了.NET 5 API的Startup.cs文件

启动.cs代码

using AutoMapper;
using EventManager.Business.Repositories;
using EventManager.Database;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;

namespace EventManager.Api
{
    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.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.AllowAnyOrigin()
                               .AllowAnyHeader()
                               .AllowAnyMethod();
                    });
                //options.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

            services.AddControllers();

            services.AddApiVersioning(x =>
            {
                x.DefaultApiVersion = new ApiVersion(2, 1);
                x.AssumeDefaultVersionWhenUnspecified = true;
                x.ReportApiVersions = true;

                // Supporting multiple versioning scheme
                x.ApiVersionReader = new UrlSegmentApiVersionReader();
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV";
                options.SubstituteApiVersionInUrl = false;
            });

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new Business.MappingProfile());
            });

            var mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Event Manager API Documentation",
                    Version = "v1",
                    Contact = new OpenApiContact
                    {
                        Email = "eric@xxxxx.com",
                        Name = "Eric Smith",
                        Url = new Uri("https://www.xxxxx.org/")
                    },
                    Description = @"Used for as a self-service for event attendees. 
                                To capture attendee details and print out attendee badges",
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://www.xxxxx.org/api/license"),
                    }
                });

                //Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("MSSqlConnection"),
            b => b.MigrationsAssembly("EventManager.Database")));

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped<EventRepository>();
            services.AddScoped<AttendeeRepository>();
            services.AddScoped<DesignationRepository>();
            services.AddScoped<EntryQuestionRepository>();
            services.AddScoped<EntryQuestionSectionRepository>();

            //Sart: To serve angular app
            services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp"; });
            //End: To serve angular app
        }

        // 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.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "EventManager.Api v1"));
            }

            app.UseRouting();

            app.UseCors(builder =>
            {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });

            app.UseAuthorization();

            //Start: To serve angular app
            app.UseDefaultFiles();
            app.UseSpaStaticFiles();

            //End: To serve angular app

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

            //Start: To serve angular app
            app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; });
            //End: To serve angular app
        }
    }
}

使用AutoMapper;
使用EventManager.Business.Repositories;
使用EventManager.Database;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.Mvc.Versioning;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.DependencyInjection.Extensions;
使用Microsoft.Extensions.Hosting;
使用Microsoft.OpenApi.Models;
使用制度;
使用System.IO;
运用系统反思;
名称空间EventManager.Api
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddCors(选项=>
{
options.AddDefaultPolicy(
生成器=>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
//options.AddPolicy(“AllowOrigin”,options=>options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
services.AddControllers();
services.addapVersioning(x=>
{
x、 DefaultApiVersion=新的ApiVersion(2,1);
x、 AssumeDefaultVersionWhenUnspecified=true;
x、 ReportApiVersions=true;
//支持多版本控制方案
x、 ApiVersionReader=新UrlSegmentApiVersionReader();
});
services.AddVersionedApiExplorer(选项=>
{
options.GroupNameFormat=“'v'VVV”;
options.substituteApprovisionInUrl=false;
});
var mappingConfig=新的MapperConfiguration(mc=>
{
mc.AddProfile(new Business.MappingProfile());
});
var mapper=mappingConfig.CreateMapper();
服务。AddSingleton(映射器);
services.AddSwaggerGen(c=>
{
c、 SwaggerDoc(“v1”),新OpenApiInfo
{
Title=“事件管理器API文档”,
Version=“v1”,
Contact=newopenapicontact
{
电子邮件=”eric@xxxxx.com",
Name=“埃里克·史密斯”,
Url=新Uri(“https://www.xxxxx.org/")
},
Description=@“用于作为活动参与者的自助服务。
要捕获与会者详细信息并打印出与会者徽章“,
许可证=新的OpenAPI许可证
{
Name=“在LICX下使用”,
Url=新Uri(“https://www.xxxxx.org/api/license"),
}
});
//为Swagger JSON和UI设置注释路径。
var xmlFile=$“{Assembly.getExecutionGassembly().GetName().Name}.xml”;
var xmlPath=Path.Combine(AppContext.BaseDirectory,xmlFile);
c、 includexmlcoments(xmlPath);
});
services.AddDbContext


错误ERR\u NAME\u NOT RESOLVED通常意味着:Chrome无法解析域名,这在大多数情况下意味着您使用了错误的域名或输入错误。
在您的情况下,您的应用程序中似乎使用了错误的顶级域。Postman=“.net”,您的应用程序=“.com”。

如果是同一个域,则不应该有选项请求。a)浏览器位置和b)请求(从网络选项卡>请求>详细信息)中的准确和完整URL是什么?如果在Postman中调用URL,会发生什么?(背景:如果出现异常,您的cors请求将失败,而您的浏览器告诉您“cors”,这实际上与cors无关,只是一个错误的url/exception/…)@ChristophLütjen请求在Postman中运行良好。它正在返回预期的数据。我已使用Postman结果编辑了该问题。@ChristophLütjen我还添加了另一个带有Chrome浏览器响应的屏幕截图。网络->状态中的错误为“(失败)net::ERR_NAME_未解决”错误ERR_NAME_NOT RESOLVED通常意味着:Chrome无法解析域名,在大多数情况下,因为您使用了错误的域名或输入错误。在您的情况下,它看起来像tld.Postman=“.net”,您的应用程序=“.com”?
headers = new HttpHeaders({
    "Authorization": "Bearer " + "XXXXXXX",
    "Content-Type": "application/json"
  });

//environment.api = 'https://myazureappname.azurewebsites.net/api/'

get(cellNumber?: string): Observable<AttendeeGetModel[]> {
    return this._http.get<AttendeeGetModel[]>(`${environment.api}v1/attendees?cellNumber=${cellNumber}`, { headers: this.headers });
  }

**Error message from Firefox browser attached**

[![enter image description here][1]][1]