1. 程式人生 > >c# WebApi之解決跨域問題:Cors

c# WebApi之解決跨域問題:Cors

error: avi 域名 1.10 settings dev ger gin .dll

什麽是跨域問題

出於安全考慮,瀏覽器會限制腳本中發起的跨站請求,瀏覽器要求JavaScript或Cookie只能訪問同域下的內容。由於這個原因,我們不同站點之間的數據訪問會被拒絕。

Cors解決跨域問題

跨域資源共享( CORS )機制允許 Web 應用服務器進行跨域訪問控制,從而使跨域數據傳輸得以安全進行。它解決跨域問題的原理是通過向http的請求報文和響應報文裏面加入相應的標識告訴瀏覽器它能訪問哪些域名的請求。

解決跨域問題實例

下面就寫一個簡單是實例來說明如何使用CORS解決跨域

1、建立測試項目

1.1、新建兩個ASP.NET Web 應用程序,作為Web站點和WebApi站點:

技術分享圖片

1.2、配置WebApi站點
在WebApiConfig.cs文件裏面配置Web API 路由,指向具體的action

//Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
    name: "DefaultApi1",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

在控制器中新建一個測試方法,用於返回請求數據:

[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    /// <summary>
    /// 得到所有數據
    /// </summary>
    /// <returns>返回數據</returns>
    [HttpGet]
    public string GetAllData()
    {
        return "Success";
    }
}

啟動Web API項目,站點端口號為:8476

1.3、配置Web站點
新建一個index測試頁面:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
    測試結果:
    <div id="div_test">
        hello world
    </div>
</body>
</html>
public ActionResult Index()
{
    return View();
}

用jquery 的 ajax處理請求:

<script>
    var ApiUrl = "http://localhost:8476/";
    $(function () {
        $.ajax({
            type: "get",
            dataType:"json",
            url: ApiUrl + "api/Account/GetAllData",
            data: {},
            success: function (data, status) {
                if (data == "success") {
                    $("#div_test").html(data);
                }
            },
            error: function (e) {
                $("#div_test").html("Error");
            },
            complete: function () {

            }

        });
    });
</script>
2、測試

在不做任何處理的情況下,運行Web項目,結果為:
技術分享圖片

可以看到瀏覽器拒絕了我們的跨域訪問。

3、使用CORS跨域

首先安裝CORS,在WebApiCors項目上面使用Nuget搜索“microsoft.aspnet.webapi.cors”,安裝第一個
技術分享圖片
當我們安裝這個包之後,現有的packages目錄下會添加兩個名稱分別為“Microsoft.AspNet.Cors.5.2.3”和“Microsoft.AspNet.WebApi.Cors.5.2.3”,針對保存其中的兩個程序集(System.Web.Cors.dll和System.Web.Http.Cors.dll)的引用被自動添加到WebApiCors項目中
技術分享圖片

然後在App_Start文件夾下面的WebApiConfig.cs文件夾配置跨域

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        //跨域配置
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi1",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

我們暫定三個“*”號,當然,在項目中使用的時候一般需要指定對哪個域名可以跨域、跨域的操作有哪些等等。這個下面介紹

重新運行:
谷歌
技術分享圖片

IE7、IE8、IE9
技術分享圖片
我都已經設置跨域了呀,怎麽IE7、8、9還是不行呢?這個時候就有必要說說CORS的瀏覽器支持問題了。網上到處都能搜到這張圖:
技術分享圖片

可以看到IE8、9只有部分瀏覽器支持,那麽如何解決IE瀏覽器支持問題呢,其實在調用處指定 jQuery.support.cors = true; 這一句就能解決IE8、9的問題了:

<script>
    jQuery.support.cors = true;
    var ApiUrl = "http://localhost:8476/";
    $(function () {
        $.ajax({
            type: "get",
            url: ApiUrl + "api/Account/GetAllData",
            data: {},
            success: function (data, status) {
                if (status == "success") {
                    $("#div_test").html(data);
                }
            },
            error: function (e) {
                $("#div_test").html("Error");
            },
            complete: function () {

            }

        });
    });
</script>

技術分享圖片

4、CORS的具體參數設置。

上文我們用的是:config.EnableCors(new EnableCorsAttribute(““, ““, “*”));,這裏的*號表示只要別人知道你的url,任何請求都能返回資源,這是不安全的,所以需要進行訪問控制。
配置方法一
在Web.Config配置:

<appSettings>
  <add key="cors:allowedMethods" value="*"/>
  <add key="cors:allowedOrigin" value="http://localhost:8610"/>
  <add key="cors:allowedHeaders" value="*"/>
</appSettings>

然後在WebApiConfig.cs文件配置

public static void Register(HttpConfiguration config)
{          
    //跨域配置
    var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];
    var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];
    var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];
    var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods)
    {
        SupportsCredentials = true
    };
    config.EnableCors(geduCors);

    //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

配置方法二
如果你只想對某一些api做跨域,可以直接在API的類上面使用特性標註即可。

[EnableCors(origins: "http://localhost:8610/", headers: "*", methods: "GET,POST,PUT,DELETE")]
public class AccountController : ApiController
{
    /// <summary>
    /// 得到所有數據
    /// </summary>
    /// <returns>返回數據</returns>
    [HttpGet]
    public string GetAllData()
    {
        return "Success";
    }
}

c# WebApi之解決跨域問題:Cors