WebApi 自定義過濾器實現支持AJAX跨域的請求

    我想關於此類話題的文章,你們一搜鋪天蓋地都是,我寫此文的目的,只是對本身學習過程的記錄,能對須要的朋友有所幫助,也百感榮幸!!!廢話很少說,直接上代碼!javascript

客戶端:很簡單的AJAX請求html

<html>
<head>
<title id='Description'>WebApi支持Ajax跨域</title> <script src="js/jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function () { $.ajax({ type: "POST", url: "https://192.168.1.9/api/values/get", success: function (persons) { alert('persons'); }, error: function () { alert('fail'); } }); }); </script> </head> <body class='default'> </body> </html>

WebApi服務端:java

1.自定義EnableCorsAttribute類,繼承於System.Web.Http.Filters.ActionFilterAttribute ,重寫OnActionExecuted方法以下jquery

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;

namespace ResourceServer
{
    public class EnableCorsAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {

       public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Origin"))
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Headers"))
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type,Accept");
            }
            if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Methods"))
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST");
            }
         }
    }
}

2.上一部完成後,也已經大功告成,此步直接在想支持跨域Controller的Action的方法上添加標記,就能實現AJAX的跨域調用了。:)ajax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.OData;
using Newtonsoft.Json;
using WebApiThrottle;

namespace ResourceServer.Controllers
{
    public class People {
        public string Name { get; set; }
        public int Age { get; set; }
    
    
    
    }
    
    public class ValuesController : ApiController
    {


        public static List<People> li = new List<People>{
        
        new People{ Name="李剛", Age=19},
        new People{ Name="王六", Age=20}

        
        };
        // GET api/<controller>
        [EnableCors]//此特性添加就支持跨域訪問了
        [HttpPost]
        [HttpGet]
        [EnableQuery()]
        [EnableThrottling(PerMinute=5)]
        public List<People> Get()
        {
            return li;
        }

    }
}
相關文章
相關標籤/搜索