2016-03-21 51 views
1

我已經將Web API 2添加到現有的vb aspx web窗體項目。並且路由進入全局asax application_start,因爲我沒有WebApiConfig的app_start文件夾,就像您在標準web api項目中一樣。我下載CORS從金塊包管理器添加試圖使CORS添加cors到aspx web api 2混合

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 
     ' Fires when the application is started 

     RouteTable.Routes.MapHttpRoute(
      name:="DefaultApi", 
      routeTemplate:="api/{controller}/{id}", 
      defaults:=New With {.id = RouteParameter.Optional} 
     ) 

    Dim cors = New EnableCorsAttribute("*", "*", "*") 
    GlobalConfiguration.Configuration.EnableCors(cors) 

    End Sub 

但每當我嘗試運行是通過jQuery的AJAX我收到打電話到我的網頁API的HTML頁面。

Cross-Origin Request Blocked: The Same Origin Policy 
disallows reading the remote resource at https://xxxxx/specialdev/api/WSFobOrigin. 
(Reason: CORS header 'Access-Control-Allow-Origin' missing) 

所以我不太清楚我缺少什麼,我試圖將它添加到每個控制器以及。

Public Class WSFobOriginController 
    Inherits ApiController 
    <EnableCors("*", "*", "*")> 
    <HttpGet> 
    <CustomAuthentication> 
    <Authorize(Roles:="WebService")> 
    Public Function logon() As IHttpActionResult 
     Return Ok("successfully loggon on") 
    End Function 

這裏是Ajax調用(我有和沒有跨域試了一下:真)

this.logon = function() { 
       $('#signin').prop('disabled', true); 
       $.ajax({ 
        url: "https://xxxxxxxx.dir.ad.dla.mil/specialdev/api/WSFobOrigin", 
        type: "GET", 
        datatype: "json", 
        crossDomain: true, 
        beforeSend: function (xhr) { 
         $('#logonSpinner').show(); 
         xhr.setRequestHeader("Authorization", "Basic " + btoa(self.userName() + ":" + self.password())); 
        }, 
        success: function (data) { 
         self.loggedon(true); 
        }, 
        error: function (xhr, status, error) { 
         $('#signin').prop('disabled', false); 
         $('#logonSpinner').hide(); 
         $('#logonError').show(); 
         self.logOnErrorMessage("Status: " + xhr.status + " Message: " + xhr.statusText) 
        } 
       }); 

      } 

只注意到一件事是有點奇怪我。當我在本地運行web api(通過visual studio)並將我的客戶端jQuery ajax調用更改爲本地url時,它可以工作。

URL Protocol Method Result Type Received Taken Initiator Wait‎‎ Start‎‎ Request‎‎ Response‎‎ Cache read‎‎ Gap‎‎ 
http://localhost:52851/api/WSFobOrigin HTTP OPTIONS 200  420 B 31 ms CORS Preflight 0 16 0 15 0 203 

URL Protocol Method Result Type Received Taken Initiator Wait‎‎ Start‎‎ Request‎‎ Response‎‎ Cache read‎‎ Gap‎‎ 
http://localhost:52851/api/WSFobOrigin HTTP GET 200 application/json 447 B 218 ms XMLHttpRequest 16 15 203 0 0 0 

,但是當我改變客戶端指向實際服務器的預檢中止,不再類型說OPTIONS它是空

URL Protocol Method Result Type Received Taken Initiator Wait‎‎ Start‎‎ Request‎‎ Response‎‎ Cache read‎‎ Gap‎‎ 
https://xxxxxxx.dir.ad.dla.mil/specialdev/api/WSFobOrigin HTTPS  (Aborted)  0 B 47 ms CORS Preflight 0 47 0 0 0 796 

一些其他職位建議增加一個過濾器,我試過了,但似乎沒有工作要麼

我M端口System.Web.Http.Filters

Public Class AllowCors 
    Inherits ActionFilterAttribute 
    Public Overrides Sub OnActionExecuted(actionExecutedContext As HttpActionExecutedContext) 
     If actionExecutedContext Is Nothing Then 
      Throw New ArgumentNullException("actionExecutedContext") 
     Else 
      actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin") 
      actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*") 
      actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type") 
      actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS") 
     End If 
     MyBase.OnActionExecuted(actionExecutedContext) 
    End Sub 
End Class 

裝潢我的allowcors

<AllowCors> 
    <EnableCors("*", "*", "*")> 
    <HttpGet> 
    <CustomAuthentication> 
    <Authorize(Roles:="WebService")> 
    Public Function logon() As IHttpActionResult 
     Return Ok("successfully loggon on") 
    End Function 

但仍沒有運氣

status: 404 
Method: OPTIONS 
Request Headers: Host: xxxxxx.dir.ad.dla.mil 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-US,en;q=0.5 
Accept-Encoding: gzip, deflate 
Origin: null 
Access-Control-Request-Method: GET 
Access-Control-Request-Headers: authorization 
Connection: keep-alive 

Response Headers: Cache-Control: private 
Content-Type: text/html 
Server: Microsoft-IIS/7.5 
X-Powered-By: ASP.NET 
X-Frame-Options: SAMEORIGIN 
Date: Wed, 23 Mar 2016 16:53:06 GMT 
Content-Length: 1245 
+0

可以嗎能夠在您的解決方案結構中的'App_code'中找到'Startup.cs'?因爲你提到你使用的是web api2 – Webruster

+0

不,這是怎麼回事呢是因爲我們有一個現有的aspx web表單應用程序,並且在事實之後我進入了nu get並添加到web api包中。所以我沒有像通常那樣使用bundle_config,route_config等典型的app_start文件夾,而是在application_start(請參閱我的文章中的第一個代碼塊)下進入全局asax。另一件令人討厭的事情是VB應用程序,它一直在尋找使用VB的web api示例。 –

+0

你可以顯示你的webconfig,並嘗試以這種方式啓用cors var var = HttpContext.Current; \t \t var response = context.Response; \t \t \t // \t使CORS \t \t response.AddHeader( 「訪問控制允許來源」, 「*」); \t \t response.AddHeader(「X-Frame-Options」,「ALLOW-FROM *」);'在Application_Start – Webruster

回答

0

您可以在三個級別配置CORS爲Web API支持:

  1. 在全球範圍內
  2. 在控制器級別
  3. 在操作層面

要配置全球範圍的的CORS支持, 首先從App_Start文件夾安裝CORS包(你已經做了) ,然後打開WebApiConfig.cs文件。(在這裏你說你沒有那個文件夾)

Dim cors = New EnableCorsAttribute("http://localhost:5901", "*", "*") 
config.EnableCors(cors) 

(當你不使用這種方法,然後我們會去下一個級別)

行動水平

<EnableCors(origins := "*", headers := "*", methods := "*")> 
    <HttpGet> 
    <CustomAuthentication> 
    <Authorize(Roles:="WebService")> 
Public Function logon() As IHttpActionResult 
     Return Ok("successfully loggon on") 
    End Function 

在上述方法中需要設置的參數,讓所有的頭,並通過設置支持所有的HTTP方法價值明星。

控制器級別

<EnableCors(origins := "*", headers := "*", methods := "*")> _ 
Public Class ClassesController 
    Inherits ApiController 
End Class 

在此需要設置參數,使所有的頭,並通過設定以星支持所有的HTTP方法。您可以使用[DisableCors]屬性從CORS支持中排除其中一項操作。

所以最後這裏有EnableCors

屬性有三個屬性傳遞到EnableCors:

  1. 起源:您可以設置一個以上的起源值以逗號分隔。如果您想要任何來源向API發出AJAX請求,請將原始值設置爲通配符值star。
  2. 請求標頭:請求標頭參數指定允許哪些請求標頭。要允許任何標頭設置值,請執行以下操作:
  3. HTTP方法:methods參數指定允許哪些HTTP方法訪問資源。要允許所有方法,請使用通配符值'*'。否則,請設置逗號分隔的方法名稱,以允許一組方法訪問資源。

所以在使用VB結合以上幾點,你需要聲明如下

<EnableCors(origins := "http://localhost:XXX,http://localhost:YYYY", headers := "*", methods := "POST,GET")> _ 
Public Class ClassesController 
    Inherits ApiController 
End Class 

更新

嘗試將此配置添加到您的網絡配置

<customHeaders> 
<add name="Access-Control-Allow-Origin" value="*" /> 
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" /> 
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /> 
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Authorization" /> 
</customHeaders> 
+0

感謝您的建議,我已經在所有三個層次上設置CORS(以及添加自定義過濾器請參閱原文)我已經看到一些帖子建議將標頭添加到server.config,但我是不允許更改該配置文件。當我在本地主機上運行時,一切正常。 (客戶端在我的桌面或其他Visual Studio解決方案上運行,並指向在本地主機上運行的Web API),CORS在進入「真實」服務器時被阻止。有沒有可以阻止我的iis 7.5服務器設置? –

+0

@ user2744722嘗試給此在webconfig'<配置> <添加名稱= 「訪問控制允許來源」 值= 「*」/> 有關IIS的設置 – Webruster

+0

所以這可以在web.config?不是server.config?因爲我不允許更改server.config –

0

控制器我想你忘記添加Microsoft.AspNet.Cors。如果您使用Visual Studio,您可以添加使用這種方式:

工具 - > NuGet包管理器 - >管理的NuGet包解決方案

你會發現Microsoft.AspNet。CORS並安裝到API項目

+0

好的。 EnableCors()可能是錯誤的, config.MapHttpAttributeRoutes(); var cors = new EnableCorsAttribute(「*」,「*」,「*」); config.EnableCors(cors); 我的Web Api配置。如果你想嘗試這個 –