Enable CORS in Asp.net web.api using Thinktecture.IdentityModel

by sunil ravulapalli /24. August 2013 05:10 /asp.net-web-api /Comments (0)

Refer to http://sunilrav.com/post/Enable-Basic-Authetication-in-Aspnet-webapi-using-ThinktectureIdentityModel to enable basic authentication.
Add this method in WebApiConfig class

private static void ConfigureCors(HttpConfiguration config)
{ 
  var corsConfig = new WebApiCorsConfiguration(); 
  corsConfig.RegisterGlobal(config); 
   corsConfig
      .ForAllResources()
      .ForAllOrigins()
      .AllowAllMethods()
      .AllowAllRequestHeaders()
      .AllowAll();
}

Call ConfigureCors in Register method in WebApiConfig class

public static void Register(HttpConfiguration config)
{ 
  var authentication = CreateAuthenticationConfiguration();  
  config.MessageHandlers.Add(new AuthenticationHandler(authentication));   
  ConfigureCors(config); 
  config.Routes.MapHttpRoute(  name: "DefaultApi",  
           routeTemplate: "api/{controller}/{id}",  
           defaults: new { id = RouteParameter.Optional } );
  config.EnableSystemDiagnosticsTracing();
}

Make sure your web.config looks like this

<system.webServer> 
  <modules runAllManagedModulesForAllRequests="false">  
    <remove name="WebDAVModule" /> 
  </modules> 
  <handlers>  
    <remove name="WebDAV"/>  
    <remove name="OPTIONSVerbHandler"/>  
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />  
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />  
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />  
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> 
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />  
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
  </handlers>
</system.webServer>
blog comments powered by Disqus