Asp.Net WebAPI跨域配置
阿新 • • 發佈:2018-12-18
至於為什麼要使用跨域,相信開發的同學都知道,這裡咱們就不必多言,咱們看下具體怎麼配置吧,
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