简体   繁体   中英

Asp.net WebApi - CORS policy

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM