почему Net core возвращает 0 в angular?

У меня есть приложение с angular и net core web api 3. У меня проблема в том, что когда токен истекает в angular, я получаю код состояния 0, но при использовании почтальона он фактически возвращает код 401 (неавторизованный). Что могло случиться? Спасибо большое за помощь.

введите описание изображения здесь

Start.cs

public void ConfigureServices(IServiceCollection services)
    {
        var appSettingsJson = AppSettingsJson.GetAppSettings();
        var tokenKey = appSettingsJson["Token:Key"];
        services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
               .AddNewtonsoftJson(ConfigureJson).AddExtensions();
        services.AddSignalR();
        services.AddCors(options =>
        {
            options.AddPolicy("EnableCORS", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); });
            options.AddPolicy("NoRestrictions", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); });
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
         .AddJwtBearer(options =>
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidateIssuer = true,
                 ValidateAudience = true,
                 ValidateLifetime = true,
                 ValidateIssuerSigningKey = true,
                 ValidIssuer = "http://localhost:5000",
                 ValidAudience = "http://localhost:5000",
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey))
             };
         });
        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, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
        else app.UseHsts();
        app.Use(async (ctx, next) =>
        {
            await next();
            if (ctx.Response.StatusCode == 204)
            {
                ctx.Response.ContentLength = 0;
            }
        });
        app.UseRouting();
        app.UseAuthorization();
        app.UseCors("EnableCORS");
        app.UseAuthentication();
        app.UseHttpsRedirection();
        //app.UseMvc();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotifyHub>("notify").RequireCors("EnableCORS");
            endpoints.MapHub<NotifyActionHub>("notifyaction").RequireCors("EnableCORS");
        });
    }

person Community    schedule 22.10.2019    source источник
comment
Похоже, ваш запрос даже не доходит до серверной части, это может быть проблема CORS. Подробнее см. Здесь stackoverflow.com/a/14507670/2120297   -  person Arlemi    schedule 22.10.2019


Ответы (1)


Я мог это решить. Я сделал это, чтобы изменить положение инструкций services.AddCors и app.UseCors ("EnableCORS"); на передовую, и это сработало отлично.

 public void ConfigureServices(IServiceCollection services)
    {
        var appSettingsJson = AppSettingsJson.GetAppSettings();
        var tokenKey = appSettingsJson["Token:Key"];
        *services.AddCors(options =>
        {
            options.AddPolicy("EnableCORS", builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); });
        });*
        services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
               .AddNewtonsoftJson(ConfigureJson).AddExtensions();
        services.AddSignalR();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
         .AddJwtBearer(options =>
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidateIssuer = true,
                 ValidateAudience = true,
                 ValidateLifetime = true,
                 ValidateIssuerSigningKey = true,
                 ValidIssuer = "http://localhost:5000",
                 ValidAudience = "http://localhost:5000",
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey))
             };
         });
        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, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
        else app.UseHsts();
        app.UseCors("EnableCORS");

        app.Use(async (ctx, next) =>
        {
            await next();
            if (ctx.Response.StatusCode == 204)
            {
                ctx.Response.ContentLength = 0;
            }
        });
        app.UseRouting();
        app.UseAuthorization();
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireCors("EnableCORS");
            endpoints.MapHub<NotifyHub>("notify").RequireCors("EnableCORS");
            endpoints.MapHub<NotifyActionHub>("notifyaction").RequireCors("EnableCORS");
        });

    }
person Community    schedule 22.10.2019