【问题标题】:ASP.Net core 1.1 Angular2 PUT request throws No Access Control OriginASP.Net core 1.1 Angular2 PUT 请求抛出无访问控制源
【发布时间】:2017-10-17 23:27:26
【问题描述】:

在我的 ASP.Net Core 1.1 中。后端我已启用 CORS,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<WebAPIDataContext>(options =>
    {
        options.UseMySql(Configuration.GetConnectionString("MysqlConnection"));
    });
    services.AddScoped<IProfileRepository, ProfileRepository>();
    services.AddScoped<IUser_TaskRepository, User_TaskRepository>();

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

    services.AddMvc();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });


}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    // global policy - assign here or on each controller
    app.UseCors("CorsPolicy");


    app.UseMvc();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });


}

从我的 angular2 前端我发出 POST 和 PUT 请求。 POST 成功但 PUT 失败给我 No 'Access-Control-Allow-Origin' header is present on the requested resource. 他们是:

  private base_url = 'http://localhost:4783/api/';

  constructor (private http: Http) {}

  createProfile(profile: ProfileModel): Observable<ProfileModel[]>{

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.base_url + 'Profile', profile , options)
    .map(this.extractData)
    .catch(this.handleError);
  }
  updateProfile(profile: ProfileModel, profileId: number): Observable<ProfileModel[]>{

    console.log(profile, profileId)

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers});

    return this.http.put(this.base_url + 'Profile' + '/' + profileId, profile , options)
    .map(this.extractData)
    .catch(this.handleError);
  }

我做错了什么?

【问题讨论】:

    标签: angular asp.net-core


    【解决方案1】:

    第一步是检查您的调试控制台,如果确实是 PUT 失败,或者是 OPTIONS 请求(浏览器预检)。如果 OPTIONS 是您必须在后端做出反应的问题。我不是 asp.net 核心方面的专家,但在 WebApi 后端中,您必须在 global.asax.cs 中执行此操作:

     protected void Application_BeginRequest()
        {
            if (Request.HttpMethod == "OPTIONS")
            {
                Response.StatusCode = (int)HttpStatusCode.OK;
                Response.AppendHeader("Access-Control-Allow-Origin", Request.Headers.GetValues("Origin")[0]);
                Response.AddHeader("Access-Control-Allow-Headers", "content-type, accept"); 
                Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                Response.AppendHeader("Access-Control-Allow-Credentials", "true");
                Response.End();
            }
        }
    

    如果 OPTIONS 不是您的问题,请仔细检查您在通话中输入的内容是否正确。如果您弄乱了调用的必要标头/参数,您经常会收到此错误(这可能会非常混乱)。

    【讨论】:

      猜你喜欢
      • 2015-12-31
      • 2022-01-18
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多