【发布时间】:2016-07-08 08:04:01
【问题描述】:
我已将 Web API 2 添加到现有的 vb aspx Web 表单项目中。并且路由进入了全局 asax application_start,因为我没有像在标准 Web api 项目中那样使用 WebApiConfig 的 app_start 文件夹。我从 nugget 包管理器下载了 CORS 添加尝试启用 CORS
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 调用我的 web 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 调用(我尝试过使用和不使用 crossDomain: true)
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)
}
});
}
刚刚注意到一件对我来说有点奇怪的事情。当我在本地(通过visual studio)运行web api并将我的客户端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
其他一些帖子建议添加我尝试过的过滤器,但似乎也不起作用
导入 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
【问题讨论】:
-
您能否在解决方案结构中的
App_code中找到Startup.cs?因为你提到你正在使用 web api2 -
不,这是怎么回事,因为我们有一个现有的 aspx web 表单应用程序,我进入 nu get 并在事后添加到 web api 包中。所以我没有像你通常那样得到典型的 app_start 文件夹,它有 bundle_config、route_config 等。相反,路由等进入 application_start 下的全局 asax(请参阅我帖子中的第一个代码块)。另一个令人讨厌的是 VB 应用程序,使用 vb 查找 web api 示例一直很困难。
-
你可以显示你的webconfig,并尝试在Application_Start中以
var context = HttpContext.Current; var response = context.Response; // enable CORS response.AddHeader("Access-Control-Allow-Origin", "*"); response.AddHeader("X-Frame-Options", "ALLOW-FROM *");这种方式启用cors -
您是否尝试将启用 cors 代码移动到路由上方的函数顶部?
-
尝试将启用 cors 移动到路由上方,还尝试将添加标头添加到全局 asax,但它抱怨我运行时有重复的标头。
标签: asp.net vb.net cors asp.net-web-api2