0

my controller accepts 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();
        }
    }

in my angular side i have service which simply does post:

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

in my component i have :

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

in my webconfig webserver:

 <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>

when i do the post request i get the following error : Access to XMLHttpRequest at 'http://localhost:49403/api/Cart?id=1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

moris62
  • 983
  • 1
  • 14
  • 41
  • you are still facing the issue? – Vivek Bani Sep 14 '20 at 07:54
  • @RajdeepDebnath 2days at work,due to this stupid error which have no idea comes from where – moris62 Sep 14 '20 at 07:55
  • my guess its coming from backend, please share the backend code or a fake version of it if privacy issue –  Sep 14 '20 at 08:02
  • @Frost which part of back end?i have already shared my controller and webconfig – moris62 Sep 14 '20 at 08:03
  • please try this https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core `builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader();` watch the accepted answer –  Sep 14 '20 at 08:06
  • sorry, i missed previously, yes you shared :) –  Sep 14 '20 at 08:07
  • @Frost thats for .NetCore?im using asp.net webapi – moris62 Sep 14 '20 at 08:08
  • what I am saying, you have to allow cors in .net (otherwise allow from angular wont work) –  Sep 14 '20 at 08:08
  • @mortezasol have a look here : https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi `app.UseCors( options => options.WithOrigins("http://example.com").AllowAnyMethod() );` –  Sep 14 '20 at 08:10
  • @mortezasol try from fiddler or postman to call your api and check if you see the error. Or you can create a new basic angular app and check. Or let's have a qucik video call we will resolve it. – Vivek Bani Sep 14 '20 at 09:35

3 Answers3

1

You need to create a CORS policy for multiple origins to access your application. That can include development, production, qa origin, and multiple headers for that.

For WEBAPI 2:

Check 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);
    }
}

Use it over your controller like:

[MyCorsPolicy]
public class TestController : ApiController
{
}

For .NET Core Application:

In ConfigureServices, if it is a ASP.net Core application, configure a CORS policy:

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

services.AddControllers();

In the configure method, write

app.UseCors() 
Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22
0

To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller, so try this:

[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
public class TestController : ApiController
{
   // your logic
}
Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
-1

Thanks all for your comments,after hours of challenging with this issue i came to this point that i have to add the following in the webApiconfig

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

with this you don't need to add anything in webconfig or controller, strange but works!

moris62
  • 983
  • 1
  • 14
  • 41
  • 1
    With this fix, you have allowed all sites to make a CORS request to your API. Using new EnableCorsAttribute("*", "*", "*") is risky for production web application. Only allow your web application to make request. https://enable-cors.org/ – Amit Kumar Singh Sep 14 '20 at 14:21
  • You can create CORS policy – Amit Kumar Singh Sep 14 '20 at 14:28