【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Error When calling WebApi请求的资源上不存在“Access-Control-Allow-Origin”标头。调用 WebApi 时出错
【发布时间】:2017-08-17 00:24:38
【问题描述】:

从我的其他项目调用 WebApi 时出现此错误。

XMLHttpRequest cannot load http://localhost:64678/api/Employees/RetriveAllEmployees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49169' is therefore not allowed access. The response had HTTP status code 500.

我知道 CORS 需要在 WebApi 项目中启用。我已经在我的 WebApi 项目中添加了以下代码。

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

但从我的其他项目调用 WebApi 时,我仍然收到此错误。

我像下面这样调用 webapi。

        $("#getEmployees").on("click", function () {
            $.ajax({
                type: 'GET',
                url: 'http://localhost:64678/api/Employees/RetriveAllEmployees',
                success: function (data) {
                    debugger;
                },
                error: function (error) {
                    debugger;
                }
            });
        });

无法理解问题所在。

【问题讨论】:

  • 您使用的是 iisexpress 还是常规 iis?

标签: c# asp.net-web-api asp.net-mvc-5


【解决方案1】:

您是否尝试添加到您的 webconfig 中?

 <system.webServer>
   <httpProtocol>
     <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>

【讨论】:

    【解决方案2】:

    你也可以试试这个。

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

    【讨论】:

      【解决方案3】:

      我已经尝试了我在网上可以找到的所有东西,包括在这个答案中给出的方法。在几乎一整天都在尝试解决这个问题之后,我找到了对我有用的解决方案。

      在文件夹 App_Start 的 WebApiConfig 文件中,注释所有代码行并添加以下代码:

          public static void Register(HttpConfiguration config)
          {
              // Web API configuration and services
              config.EnableCors();
              var enableCorsAttribute = new EnableCorsAttribute("*",
                                                 "Origin, Content-Type, Accept",
                                                 "GET, PUT, POST, DELETE, OPTIONS");
              config.EnableCors(enableCorsAttribute);
              // Web API routes
              config.MapHttpAttributeRoutes();
      
              config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  //routeTemplate: "api/{controller}/{id}",
                  routeTemplate: "api/{controller}/{action}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
              config.Formatters.Add(new BrowserJsonFormatter());
          }
      
          public class BrowserJsonFormatter : JsonMediaTypeFormatter
          {
              public BrowserJsonFormatter()
              {
                  this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
                  this.SerializerSettings.Formatting = Formatting.Indented;
              }
      
              public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
              {
                  base.SetDefaultContentHeaders(type, headers, mediaType);
                  headers.ContentType = new MediaTypeHeaderValue("application/json");
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2015-10-29
        • 1970-01-01
        • 2017-09-28
        • 2017-08-20
        • 2013-11-29
        • 2014-07-28
        • 2014-01-19
        相关资源
        最近更新 更多