Asp.net Web Api 解决跨域问题

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

namespace KingT.Web.HIS.Sys
{
    public class SupportCrossDomainAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var resHeaders = actionExecutedContext.Response.Headers;

            if (AllowCredentials)
            {
                resHeaders.Add("Access-Control-Allow-Credentials", "true");
            }

            resHeaders.Add("Access-Control-Allow-Origin", Origin ?? "*");

            base.OnActionExecuted(actionExecutedContext);
        }

        public bool AllowCredentials { get; set; }
        public string Origin { get; set; }
    }
}

在项目中添加上面这个类 命名空间根据自己的进行修改。 然后在每个需要跨域调用的接口上添加[SupportCrossDomainAttribute]特性

[SupportCrossDomainAttribute]
        [HttpGet]
        [Route("Status")]
        public IHttpActionResult Status()
        {
            var obj = new object[] {
                 new{Id="-1" ,Text="全部" },
                 new{Id="1" ,Text= "在用" },     
                 new{Id="0" ,Text= "停用" }
            };
            return Ok(obj);
        }

 

posted @ 2017-05-09 14:03  阿波  阅读(516)  评论(0编辑  收藏  举报