解决了如何使用.Net Core Rest Api在Angular Web应用程序上进行连接?

时间:2019-03-21 09:17:03

标签: angular rest asp.net-core

我正在尝试在Angular Web应用程序中请求我的.Net Core REST Api。 我已经阅读了有关启用CORS的知识,所以我做了this

REST-Startup.cs

select try_parse([date] as date using 'en-US') from [your_table]

REST-CorsMiddleware.cs

    public class Startup
    {
       public Startup(IConfiguration configuration)
       {
           Configuration = configuration;
       }

       public IConfiguration Configuration { get; }

       public void ConfigureServices(IServiceCollection services)
       {
           services.AddMvc();
           services.AddCors();
           services.AddCors(options => {
               options.AddPolicy("CorsPolicy",
                   builder => builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials());
           });
       }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
       {
           if (env.IsDevelopment())
           {
               app.UseDeveloperExceptionPage();
           }
           else
           {

               app.UseHsts();
           }

           app.UseHttpsRedirection();
           app.UseMvc();
           app.UseCors("CorsPolicy");
           app.UseCorsMiddleware();
       }
   }

在app.module.ts中,我确实从'@ angular / common / http'导入HttpClientModule

角度-service.ts

public class CorsMiddleware
{
    private readonly RequestDelegate _next;
    public CorsMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
        httpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
        httpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
        return _next(httpContext);
    }
}
public static class CorsMiddlewareExtensions     {
    public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CorsMiddleware>();
    }
}

Angular-component.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MapService {
  constructor(private hclient: HttpClient) { }
  create():Observable<string>{
    return this.hclient.get<string>("http://localhost:44300/api/values/1");
  }
}

奇怪的是,它不能一起工作,但可以分开工作:

也许一些有用的信息? Pending requests (keeps pending a long time) Header information Error log Angular httpRequest to ASP Core rest

这就像我的REST Api仍在阻止此Angular http请求一样,我在做什么错?

问题已解决: -使用https而不是http。

0 个答案:

没有答案