由于CORS错误,无法从角度到后端执行POST请求

问题描述

我的控制器接受fromBody

 public async Task<IHttpActionResult> Post([FromBody]int  id)
    {
        using (var tx = _session.BeginTransaction())
        {
            var p = await _session.GetAsync<Product>(id);
            var c = await _session.QueryOver<Cart>().Where(x => x.ProductId == id).SingleOrDefaultAsync();

            if (p != null)
            {
                if (c == null)
                {
                    Cart cItem = new Cart
                    {
                        Name = p.Name,Picture = p.Picture,Price = p.Price,Quantity = 1,ProductId = p.Id,};
                    await _session.SaveAsync(cItem);
                }
                else
                {
                    c.Quantity = c.Quantity + 1;

                    await _session.SaveAsync(c);
                }
            }

            await tx.CommitAsync();

            return Ok();
        }
    }

在我的侧面,我提供的服务只是简单地发布:

          addTocardUrl="http://localhost:49403/api/Cart";
      constructor(private http: HttpClient) { }
      addToCart(x){   
      return this.http.post(this.addTocardUrl,{},{ params:{id:x}});
      }

在我的组件中,我有

 addToCard(id){
this.service.addToCart(id).subscribe();
}

在我的webconfig网络服务器中:

 <httpProtocol>
      <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>
  </httpProtocol>

当我执行发布请求时,出现以下错误: 通过CORS策略已阻止从来源“ http:// localhost:4200”访问“ http:// localhost:49403 / api / Cart?id = 1”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。

解决方法

您需要为多个来源创建CORS policy才能访问您的应用程序。其中可以包括开发,生产,qa起源以及为此的多个标头。

对于WEBAPI 2

选中CORS Policy here

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,AllowMultiple = false)]
public class MyCorsPolicyAttribute : Attribute,ICorsPolicyProvider 
{
    private CorsPolicy _policy;

    public MyCorsPolicyAttribute()
    {
        // Create a CORS policy.
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,AllowAnyHeader = true
        };

        // Add allowed origins.
        _policy.Origins.Add("http://myclient.azurewebsites.net");
        _policy.Origins.Add("http://www.contoso.com");
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
    {
        return Task.FromResult(_policy);
    }
}

在您的控制器上使用它,例如:

[MyCorsPolicy]
public class TestController : ApiController
{
}

对于.NET Core应用程序

在ConfigureServices中,如果它是ASP.net Core应用程序,则配置CORS策略:

services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,builder =>
                      {
                          builder.WithOrigins("http://example.com","http://www.contoso.com")
                                              .AllowAnyHeader()
                                              .AllowAnyMethod();
                      });
});

services.AddControllers();

在configure方法中,写

app.UseCors() 
,

要启用跨域请求,请将[EnableCors]属性添加到您的Web API控制器,因此请尝试以下操作:

[EnableCors(origins: "http://localhost:3000",headers: "*",methods: "*")]
public class TestController : ApiController
{
   // your logic
}
,

感谢您的评论,经过数小时的挑战之后,我才说到这一点,我必须在webApiconfig中添加以下内容

 var corsAttr = new EnableCorsAttribute("*","*","*");
        config.EnableCors(corsAttr)

使用此功能,您无需在webconfig或控制器中添加任何内容,虽然很奇怪,但是可以使用!