1. 程式人生 > >Asp.net Web Api 解決跨域問題

Asp.net Web Api 解決跨域問題

asp oss ros ner div exec space out color

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

Asp.net Web Api 解決跨域問題