Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.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
操作后在Angular 6中提出访问控制允许原点问题_Angular_Asp.net Core - Fatal编程技术网

操作后在Angular 6中提出访问控制允许原点问题

操作后在Angular 6中提出访问控制允许原点问题,angular,asp.net-core,Angular,Asp.net Core,我可以在没有CORS问题的情况下执行“获取”操作,但无法在Angular 6中执行“发布”操作。得到 请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为500 我有两种尝试。但问题并没有解决 createCustomer(Customer) { console.log(Customer); return this.http.post(this._global.baseUrl + '/Customer/Create

我可以在没有CORS问题的情况下执行“获取”操作,但无法在Angular 6中执行“发布”操作。得到 请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为500

我有两种尝试。但问题并没有解决

  createCustomer(Customer) {
console.log(Customer);
return this.http.post(this._global.baseUrl + '/Customer/CreateCustomer', Customer, { 
  headers: new HttpHeaders({
    "Content-Type": "application/json"        
  })      
});      
}

第二种方式:

      createCustomer(Customer) {
    console.log(Customer);
    return this.http.post(this._global.baseUrl + '/Customer/CreateCustomer', JSON.stringify(Customer), this._global.httpOptions)
  }
标题类:

 export class AppGlobals {
readonly baseUrl: string = 'http://localhost:50264/api';
  readonly httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json"
    })    
  };
}
ASP.Net核心API代码: Startup.cs代码:

services.AddCors(options =>
        {
            options.AddPolicy("AllowCors",
            builder => builder.WithOrigins("http://localhost:50264")
            .AllowAnyHeader()
            .AllowAnyOrigin()
            .AllowAnyMethod()
            );
        });
        services.AddMvc();   




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

        app.UseCors("AllowCors");
        app.UseMvc();
        //app.Run(async (context) =>
        //{
        //    throw new Exception("Example exception");
        //});
    }        
控制器代码:

// POST: api/Customer/CreateCustomer    
    [EnableCors("AllowCors")]
    [ActionName("CreateCustomer")]        
    public JsonResult CreateCustomer([FromBody]Customer customer)
    {
这些是错误屏幕

屏幕2:

邮差屏幕:

以下是我们目前的做法

我们有一个
httpoptionclass
,其中包含以下代码

export const httpOptions = {
  headers: new HttpHeaders({
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*"
  })
};
我们有一个服务类,它注入了
HttpClient
服务,下面是我们的
POST
操作代码

saveCustomer (customer: Customer ): Observable<any> {
    return this.httpClient.post<Customer>(
      environment.baseUrl + "/customers",
      customer,
      httpOptions
    );
  }
创业班

public void ConfigureServices(IServiceCollection services)
        {
        services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("AllowSpecificOrigin", policy =>
                {
                    var corsUrlSection = Configuration.GetSection("AllowedOrigins");
                    var corsUrls = corsUrlSection.Get<string[]>();
                    policy.WithOrigins(corsUrls)
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        app.UseCors("AllowSpecificOrigin");
        }

首先,检查是否到达终点。如果出现500个错误和CORS问题,则很有可能代码内部操作出现问题

将源代码更改为
http://localhost:4200

services.AddCors(options =>
{
    options.AddPolicy("AllowCors", builder => 
         builder.WithOrigins("http://localhost:4200") // instead of 50264
        .AllowAnyHeader()
        .AllowAnyOrigin()
        .AllowAnyMethod()
    );
}
或者将其添加到列表中

services.AddCors(options =>
{
    options.AddPolicy("AllowCors", builder => 
         builder.WithOrigins("http://localhost:50264", "http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyOrigin()
        .AllowAnyMethod()
    );
}

这将解决CORS部分。如果您仍然收到HTTP 500错误,则错误发生在CreateCustomer方法的某个地方。

刚才我将代码更改为:

createCustomer(customer: Customer) {
let body = {
  "name": customer.name,
  "email": customer.email,
  "primaryPhone": customer.primaryPhone,
  "alternatePhone": customer.alternatePhone,
  "address1": customer.address1,
  "address2": customer.address2,
  "address3": customer.address3,
  "city": customer.city,
  "state": customer.state,
  "country": customer.country,
  "zip": customer.zip,
};
return this.http.post(this._global.baseUrl + '/Customer/CreateCustomer', body, { 
  headers: new HttpHeaders({
    "Content-Type": "application/json"        
  })      
}); 

看起来您需要在服务器上列出您的域的白名单。此响应的HTTP状态代码为500。当ASP.NET核心项目中出现异常时,CORS标头将被清除。您应该尝试找出引发异常的原因。您不需要设置
“内容类型”:“application/json”
,默认情况下会这样做。如果服务端点需要JSON对象,则在POST请求中发送JSON对象之前,也不应将其字符串化。@murthy,@kirk larkin是正确的。Postman不会发出XHR请求,除非您特别添加带有XMLHttpRequest的
X-request-With
头。将这些添加到您的请求中,看看它是否中断。@murthy我在您的邮递员请求中没有看到
X-Requested-With
标题。如果不存在,则这些是正常的GET请求,与Angular的HttpClient.createCustomer(customer:customer):Observable{let body={“name”:customer.name,“email”:customer.email,“primaryPhone”:customer.primaryPhone,“alternatePhone”:customer.alternatePhone,“address1”:customer.address1,“address2”:customer.address2,“address3”:customer.address3,“city”:customer.city,“state”:customer.state,“country”:customer.country,“zip”:customer.zip,};返回此.http.post(this.\u global.baseUrl+'/customer/CreateCustomer',body,this.\u global.httpOptions).map(this.extractData).catch(this.handleErrorObservable);}在这些改变之后。一切正常。@murthy我忘记添加那个代码了。我已经更新了答案。所以我想现在你有了一个有效的代码。如果这有帮助,请把它作为正确的答案。这将对其他人有帮助。嗨,@Ivan这不是CORS的问题。我只是从Angular发送数据,在let body={“name”:customer.name}然后更改了CreateCustomer方法主体内容。嗨,@Damith,你明白我的意思吗?我无法发布答案。如果你理解我的解决方案,请根据我的更改发布答案。根据我个人经验,“访问控制允许来源”不仅取决于CORS问题。在我的上述答案中,我通过了data转换为Json格式。之后,我的CORS问题得到了解决。我在API和Angular上花费了太多时间。但这个问题仅限于Angular。
services.AddCors(options =>
{
    options.AddPolicy("AllowCors", builder => 
         builder.WithOrigins("http://localhost:4200") // instead of 50264
        .AllowAnyHeader()
        .AllowAnyOrigin()
        .AllowAnyMethod()
    );
}
services.AddCors(options =>
{
    options.AddPolicy("AllowCors", builder => 
         builder.WithOrigins("http://localhost:50264", "http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyOrigin()
        .AllowAnyMethod()
    );
}
createCustomer(customer: Customer) {
let body = {
  "name": customer.name,
  "email": customer.email,
  "primaryPhone": customer.primaryPhone,
  "alternatePhone": customer.alternatePhone,
  "address1": customer.address1,
  "address2": customer.address2,
  "address3": customer.address3,
  "city": customer.city,
  "state": customer.state,
  "country": customer.country,
  "zip": customer.zip,
};
return this.http.post(this._global.baseUrl + '/Customer/CreateCustomer', body, { 
  headers: new HttpHeaders({
    "Content-Type": "application/json"        
  })      
});