ASP.Net核心1.1 Angular2 PUT请求抛出无访问控制源

时间:2017-05-18 08:44:54

标签: angular asp.net-core

在我的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);
  }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

第一步是检查调试控制台是否确实是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不是您的问题,请仔细检查您是否在呼叫中输入了正确的输入。如果你搞砸了调用所需的标题/参数,你会经常遇到这个错误(这可能非常令人困惑)。