将cors添加到ASPX Web API 2 Hybrid [英] adding cors to aspx web api 2 hybrid

查看:71
本文介绍了将cors添加到ASPX Web API 2 Hybrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Web API 2添加到现有的vb aspx Web窗体项目中.由于我没有标准Web api项目中的WebApiConfig的app_start文件夹,因此路由进入了全局asax application_start.我从nugget软件包管理器中下载了CORS,并尝试启用CORS

I've added Web API 2 to an existing vb aspx web forms project. and the routing went into the global asax application_start because I do not have an app_start folder with WebApiConfig as you do in a standard web api project. I downloaded CORS from the nugget package manager add attempted to enable 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页面时,

however whenever I attempt to run an html page that is making calls to my web api through jquery ajax I receive.

  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)

所以我不太确定我是否想将其也添加到每个控制器中.

So I'm not quite sure what I am missing I attempting adding it to each controller as well.

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)

Here is the ajax call (I tried it with and without the 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时.

just noticed one more thing that is a bit odd to me. when I run the web api locally (through visual studio) and change my client jquery ajax call to the local url it works.

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,它为空

but when I change the client to point to the actual server the preflight aborts and the type no longer says OPTIONS it is null

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

其他一些帖子建议添加一个我尝试过的过滤器,但这似乎也不起作用

some other posts had suggested adding a filter which I tried but that does not seem to work either

导入System.Web.Http.Filters

Imports 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装饰我的控制器

and decorating my controller with 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

推荐答案

您可以在三个级别上配置对Web API的 CORS 支持:

You can configure CORS support for the Web API at three levels:

  1. 在全球范围内
  2. 在控制器级别
  3. 在操作级别

要在全局级别上配置CORS支持, 首先安装CORS软件包(您已经这样做了) 然后从App_Start文件夹中打开WebApiConfig.cs文件.(在这里您说您没有该文件夹)

To configure CORS support at the global level, first install the CORS package (Which you already did) and then open WebApiConfig.cs file from App_Start folder.(here you said you dont have that folder)

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

(由于您未使用该方法,因此我们将进入下一个级别)

(As you are not using that method, then we will go to next Level)

操作级别

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

在上述方法中,您需要设置参数以允许所有标头并通过将value设置为star支持所有HTTP方法.

In the above method you need to set parameters to allow all the headers and support all the HTTP methods by setting value to star.

控制器级别

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

在这种情况下,您需要设置参数以允许所有标头并通过将value设置为star支持所有HTTP方法.您可以使用[DisableCors]属性从CORS支持中排除其中一项操作.

In this you need to set parameters to allow all the headers and support all the HTTP methods by setting value to star. you can exclude one of the actions from CORS support using the [DisableCors] attribute.

所以最后这是EnableCors的属性

So finally Here are the Attributes of EnableCors

有三个传递给EnableCors的属性:

There are three attributes pass to EnableCors:

  1. 来源:您可以设置多个起源值,以逗号分隔.如果您希望任何来源向API提出AJAX请求,则将来源值设置为通配符值星号.
  2. 请求标头:请求标头"参数指定允许哪些请求标头.允许将任何标题设置值设置为*
  3. HTTP方法:Methods参数指定允许哪些HTTP方法访问资源.要允许所有方法,请使用通配符值"*".否则,请设置以逗号分隔的方法名称,以允许方法集访问资源.
  1. Origins: You can set more than one origins value separated by commas. If you want any origin to make AJAX request to the API then set origin value to wild card value star.
  2. Request Headers: The Request header parameter specifies which Request headers are allowed. To allow any header set value to *
  3. HTTP Methods: The methods parameter specifies which HTTP methods are allowed to access the resource. To allow all methods, use the wildcard value '*'. Otherwise set comma separated method name to allow set of methods to access the resources.

因此,结合VB中的上述几点,您需要声明如下

So combining above points in VB you need to Declare as below

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

更新

尝试将此配置添加到您的网络配置

Try to Add this Config to your web-config

<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>

这篇关于将cors添加到ASPX Web API 2 Hybrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆