WebApi 自定义过滤器实现支持AJAX跨域的请求

    我想关于此类话题的文章,大家一搜铺天盖地都是,我写此文的目的,只是对自己学习过程的记录,能对需要的朋友有所帮助,也百感荣幸!!!废话不多说,直接上代码!

客户端:很简单的AJAX请求

<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服务端:

1.自定义EnableCorsAttribute类,继承于System.Web.Http.Filters.ActionFilterAttribute ,重写OnActionExecuted方法如下

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的跨域调用了。:)

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

    }
}

 

转载于:https://www.cnblogs.com/Y-X-DONG/p/4798033.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值