Search code examples
asp.netgoogle-chromecorsasp.net-web-api2dhclient

Web API 2 EnableCors not working when I post data with DHC Chrome extension


I am developing a Web API 2 project and I using EnableCors attribute like this:

Controller:

[EnableCors(origins: "http://localhost:32454, http://localhost:25234", headers: "*", methods: "POST")]

WebApiConfig:

config.EnableCors();

Web.config:

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

When I am posting data to my Web API via DHC Chrome extension, my controller is working fine. But, I set two origin. I don't want to access my Web API via DHC. Because, I didn't allow it.

What should I do?


Solution

  • I usually use Owin with Web Api and this should resolve:

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
    
            WebApiConfig.Register(config);
            ConfigureOAuth(app);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
    }