AngularJS Allow-Origin to WebApi2

2019-08-02 18:27发布

问题:

I want to host my API on a separate domain. I have configured my auth-interceptor for token in angular with a bearer:

config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('token');

In my My WebApi2 I have configured the WebApiConfig with cors.

var cors = new EnableCorsAttribute("http://mydomain.com", "*", "*");
config.EnableCors(cors);

And in web.config of the API I also included:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>

I still can´t access the api due to origin not allowed. Can I add something more in my header of the auth-interceptor in angular or what do I need to do?

回答1:

In web.config of API, include the below mentioned code:

<system.webServer>    
    <httpProtocol>
          <customHeaders>
            <remove name="X-Powered-By" />
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
          </customHeaders>
        </httpProtocol>
 <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="WebDAV" />
      <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>

I hope this helps.

Thanks.



回答2:

your Angular.js interceptor settings are ok. I've got a public project with your same scenario, with OAuth+Owin authentication. The steps I followed are:

  1. Installation of Microsoft.Owin.Cors library
  2. Creation of custom section config to enable/config CORS
  3. Creation of custom CORS Policy class (with the origins to enable)
  4. Setup of CORS policy depending on configurations

Hope this helps



回答3:

I've had the same issue before and what worked for me was to remove the settings from the web.config and just leave the configuration settings in the WebApiConfig class

See this answer for more details