至于为什么要使用跨域,相信开发的同学都知道,这里咱们就不必多言,咱们看下具体怎么配置吧,
1.安装跨域组件
建立好WEBAPI项目后,在visual studio中,工具--》NuGet程序包管理器-->程序包管理控制台,输入如下命令
Install-Package Microsoft.AspNet.WebApi.Cors
安装完后,目录下会多如下两个DLL Microsoft.AspNet.Cors , Microsoft.AspNet.WebApi.Cors
2.在WebApiConfig类中添加如下代码,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Web.Http.Cors;
namespace CrmWebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//打开跨域支持
// config.EnableCors();
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
// Web API 配置和服务
// 将 Web API 配置为仅使用不记名令牌身份验证。
//config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
这样简简单单就实现跨域配置了
参考了如下两位道友的博客,非常干净
https://www.cnblogs.com/wangyu3619/p/5285708.html
http://www.cnblogs.com/hnsongbiao/p/9375997.html