2016-11-01 43 views
0

我試圖在名爲YDN-DB的框架中訪問我的WebApi服務。它是一個本地存儲類型數據庫。它允許你從一個URL加載和 我試圖用一個十字原點調用。WebAPI2 - Cross Origin腳本問題

這是創建XMLHttpRequest,並使得調用的代碼:

var xhr = new XMLHttpRequest(); 
xhr.open('GET', url, true); 
var me = this; 
xhr.onload = function(e) { 
    var lines = xhr.responseText.split('\n'); 
    var documents = []; 
    for (var i = 0; i < lines.length; i++) { 
     var data = lines[i].split(';'); 
     if (data.length == 2) { 
      for(i=0; i<data.length; i++) { 
       // Here, I will be loading the records into the YDN-DB. 
      } 
     } 
    } 
    var msg = Documents.length + ' Documents loaded, indexing...'; 
    me.setStatus(msg); 
    var i=0; 
    var load = function(i) { 
     var n = 50; 
     me.db.put('Document', docs.slice(i, i + n)).then(function(keys) { 
     i = i + n; 
     if (i < docs.length) { 
      this.setStatus(msg + ' ' + i); 
      load(i); 
     } else { 
      this.setStatus(msg + ' done.'); 
     } 
     }, function(e) { 
     throw e; 
     }, me); 
    }; 
}; 
xhr.send(); 

我不斷收到一個錯誤,我想不通爲什麼。

XMLHttpRequest cannot load http://localhost:51946/api/Archive/c4020343622d57162cbdc11e603a49d93d64018e5c/1026697/1/10000/D. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8040' is therefore not allowed access. 

這是從我的控制器我的WebAPI的功能,我已經啓用CORS以及從原點:

[HttpGet] 
[ResponseType(typeof(List<string>))] 
[Route("api/Archive/{LogonTicket}/{PID}/{MinRow}/{MaxRow}/{Direction}")] 
[EnableCors("http://localhost:8040", // Origin 
      "Accept, Origin, Content-Type, Options",        // Request headers 
      "GET",                 // HTTP methods 
      PreflightMaxAge = 600             // Preflight cache duration 
)] 
public object Archive(string LogonTicket, int PID, int MinRow, int MaxRow, string Direction) 
{ 
    if (svc.ValidateTicket(LogonTicket, PID)) 
    { 
     List<string> e = mp.GetArchiveJson(PID.ToString(), MinRow, MaxRow, Direction); 
     return e; 
    } 
    else 
    { 
     throw new AuthenticationException("Invalid LogonTicket"); 
    } 
} 

任何想法?我是否需要向XMLHttpRequest添加第二個調用?

+0

推測你已經安裝了'Microsoft.AspNet.WebApi.Cors' NuGet包。你是否也在你的啓動中運行'HttpConfiguration.EnableCors()',根據文檔? https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors – Snixtor

+0

我想我可能已經忘記這麼做了,我會檢查。 – MB34

+0

好吧,發佈,我會接受。天哪,我不能相信我忘了那個 – MB34

回答

0

請務必按照關於「啓用CORS」的the documentation中的所有步驟操作。有三件必要的事情:

  1. 安裝NuGet包。 Install-Package Microsoft.AspNet.WebApi.Cors
  2. 在HttpConfiguration上啓用CORS。通常這是一個靜態方法:Register(HttpConfiguration config),包括致電config.EnableCors()
  3. 使用EnableCors屬性例如裝飾您的控制器或方法。 [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]

鑑於你例如使用EnableCors屬性的,很明顯,你已經得到了#3,其中有#1作爲先決條件,所以你也有這一點。看起來你錯過了#2。