2017-01-12 123 views
1

我是新來的Rest API。我正嘗試從我的應用程序調用跨域rest API。 這裏是我的代碼 -其餘API - 405方法不允許

$.ajax({ 
      type: "GET", 
      async: false, 
      url: 'http://xx.xxx.xxx.xx:9003/GetProjectList', 
      contentType: "application/json", 
      dataType: "json", 
      traditional: true, 
      CrossDomain: true, 
      data: { 
       StartDate: '2016-12-20', 
       EndDate: '2017-01-10' 
      }, 
      success: function (data) { 
       alert("Success"); 
       alert(data); 

      }, 

      error: function (xhr, textStatus, errorThrown) { 
       alert("Failed"); 
       alert(xhr); 
       alert(textStatus); 
       alert(errorThrown); 

      } 
     }); 

但我得到的錯誤作爲

OPTIONS http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10 405 (Method Not Allowed) 

XMLHttpRequest cannot load http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64207' is therefore not allowed access. The response had HTTP status code 405. 

我在這裏缺少什麼?任何代碼或配置?

如果我直接從瀏覽器或郵遞員打那個URL,它的工作正常。但它不適用於應用程序。

+0

這是基本的CORS錯誤。您應該在響應頭中設置必需的CORS頭。有很多SO回答可用於此。順便說一句,你的服務是web-api還是wcf-rest?您不應該將兩個標籤添加在一起 – Developer

+0

您只需要允許CORS。知道,它並不總是工作! –

+0

爲什麼在GET請求上設置Content-Type? – Quentin

回答

0

我認爲這個問題是一個CORS問題(有時405也意味着你正在調用錯誤的HTTP動詞的API)..但是讀你的例外,它看起來像一個CORS問題..試試這個:

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.yoursite.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); 

      } 
     } 
    } 

嘗試將其放入您的startUp文件並安裝Microsoft.Owin.Cors nuget包