WebApi解决跨域

直接撸代码

namespace WRFMoblieWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // 解决跨域
            //跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            // Web API 配置和服务
            // Web API 路由
            config.MessageHandlers.Add(new RequestHandler()); //手动过滤
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //设置Datetime 格式化
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                new IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                }
                );
        }
    }
}

webconfig中    <httpProtocol> <customHeaders> 节点不能写配置,测试完美通过。

然而在自定义的返回类里还是有快鱼问题,单独贴上解决代码

 /// <summary>
        /// 构造自定义HTTP响应消息
        /// </summary>
        /// <param name="error"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private HttpResponseMessage SendError(string error, HttpStatusCode code )
        {
            var response = new HttpResponseMessage();//解决自定义返回消息跨域
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
                //HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
                response.Content = new StringContent(error.Replace(@"\\", @"\"));
            response.StatusCode = code;
            return response;
        }

猜你喜欢

转载自blog.csdn.net/tink_tl/article/details/81699271