1

I have Asp.net web api project as a backend and react js as front-end I'm trying to make an api requests through my React to get or post data from or to the database using the api endpoints i created an the backend.

first time i had CORS error for both GET and POST requests, then i added this to my Web.config file

<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" /> <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Pragma, Cache-Control, Authorization " /> </customHeaders> </httpProtocol> </system.webServer> 

now GET is working fine but POST is not working

Get

public IHttpActionResult Get(string password) { if (password == "000") { using (DbModel dbModel = new DbModel()) { return Ok(dbModel.Provider_status.ToList()); } } else { return null; } } 

POST

[HttpPost] public IHttpActionResult Post(List<Provider_status> rows) { try { using (DbModel dbModel = new DbModel()) { dbModel.Provider_status.AddRange(rows); dbModel.SaveChanges(); } } catch { } return Ok("record created"); } 
1

2 Answers 2

3

I've implemented same but got error for multiple origins. When I pass multiple origins with comma separated then again I got CORs error. So I've implemented Custom CORS policy providers.

I'm having same issue with PUT method. The solution is Custom CORS policy providers.

The [EnableCors] attribute implements the ICorsPolicyProvider interface. You can provide your own implementation by creating a class that derives from Attribute and implements ICorsPolicyProvider.

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class MyCorsPolicyProvider : Attribute, ICorsPolicyProvider { private CorsPolicy _policy; public MyCorsPolicyProvider() { // 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); } } 

Now you can apply the attribute any place that you would put [EnableCors].

[MyCorsPolicy] public class TestController : ApiController { .. // 

For example, a custom CORS policy provider could read the settings from a configuration file.

As an alternative to using attributes, you can register an ICorsPolicyProviderFactory object that creates ICorsPolicyProvider objects.

public class CorsPolicyFactory : ICorsPolicyProviderFactory { ICorsPolicyProvider _provider = new MyCorsPolicyProvider(); public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request) { return _provider; } } 

To set the ICorsPolicyProviderFactory, call the SetCorsPolicyProviderFactory extension method at startup, as follows:

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.SetCorsPolicyProviderFactory(new CorsPolicyFactory()); config.EnableCors(); // ... } } 

It should work, But after your deployment if it will not work then Please add the below configuration in your web.config

<system.webServer> <modules> <remove name="WebDAVModule" /> </modules> <handlers> <remove name="WebDAV" /> <remove name="OPTIONSVerbHandler" /> <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" /> </handlers> </system.webServer> 

After deployment just do IISRESET or restart App pool

Thank you

Sign up to request clarification or add additional context in comments.

Comments

1

Install the Cors package.

  1. Install-Package Microsoft.AspNet.WebApi.Cors

  2. Enable Cors in your WebApiConfig

 { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } 
  1. Decorate your controller like this
 [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")] public class TestController : ApiController 

Source: Microsoft Documentation

4 Comments

can i set origins: "*"?
[EnableCors(origins: "", headers: "", methods: "")] i added this to my controller, and now GET and POST do not work and i get this error message: blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values ', *', but only one is allowed.
You can add a global policy to your web config like: //Global Policies EnableCorsAttribute cors = new EnableCorsAttribute("", "", "GET,POST,UPDATE"); config.EnableCors(cors); or //Enable CORS for specific controller config.EnableCors(); [EnableCorsAttribute("", "", "*")]
i found the solution in here stackoverflow.com/questions/54632435/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.