Cors不在web api2项目中工作

时间:2017-01-13 08:48:29

标签: angularjs cors asp.net-web-api2

您好我正在开发web api2项目。我在服务器192.168.0.213托管应用程序,我试图访问如下方法。

 this.getSubs = function () {
        var url = 'http://192.168.0.213:7777/api/User_Creation/';
        return $http.get(url).then(function (response) {
            return response.data;
        });
    }

上面的函数返回没有问题的数据。 例如我的下面的方法,如PUT,DELETE和POST等动词不起作用。

this.saveSubscriber = function (sub) {
        return $http({
            method: 'post',
            data: JSON.stringify(sub),
            url: 'http://192.168.0.213:7777/api/User_Creation/',
            contentType: "application/json"
        });
    }

我尝试了很多方法仍然没有采用任何方法。目前我在web.config文件中有以下代码。

 <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,DELETE" />
      </customHeaders>

此外,我在webapiconfig.cs文件中有以下代码行。

private static void EnableCrossSiteRequests(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute(
                origins: "*",
                headers: "*",
                methods: "*");
            config.EnableCors(cors);
        }

此外,我在控制器中有以下代码行。仍然无法正常工作。

  [EnableCors(origins: "http://192.168.0.213:7777", headers: "*", methods: "*")]

我也评论道。我尝试了所有的方式只有GET动词才能正常工作。我的插入更新删除操作无效。我可以知道我做错了什么吗?我可以得到一些帮助,因为我尽我所能仍然没有运气。谢谢大家。

2 个答案:

答案 0 :(得分:1)

你应该有[EnableCors(origins: "http://192.168.0.54", headers: "*", methods: "*")]换句话说,你的EnableCors应该指定尝试连接的客户端,而不是服务器本身

答案 1 :(得分:1)

尝试这样的事情:(对我来说工作完美):

Startup.cs文件:(install Microsoft.Owin.Cors nuget packages before

using Goocity.API;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup("API", typeof(Goocity.API.Startup))]

namespace Goocity.API
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            #region TO UNCOMMENT WHEN IS IN PRODUCTION
            //var corsPolicy = new CorsPolicy
            //{
            //    AllowAnyMethod = true,
            //    AllowAnyHeader = true,
            //    SupportsCredentials = true,
            //    Origins = { "http://www.mysite.it" }
            //};

            //app.UseCors(new CorsOptions
            //{
            //    PolicyProvider = new CorsPolicyProvider
            //    {
            //        PolicyResolver = context => Task.FromResult(corsPolicy)
            //    }
            //});
            #endregion TO UNCOMMENT WHEN IS IN PRODUCTION

            app.UseCors(CorsOptions.AllowAll);
            ConfigureAuth(app);

        }
    }
}

然后你的webconfig :(在system.webserver部分中)

<system.webServer>
    <httpProtocol>
      <customHeaders>

        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token, Cache-Control" />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <remove name="FormsAuthentication" />
    </modules>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
    <!--<rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
        </rule>

      </rules>
    </rewrite>-->

    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <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>

希望它能帮到你!! ...