最近在寫個webapi 的接口服務,正常後端請求沒什麼問題。
但想對方可以直接用ajax 進行調用,那麼接口就得支持跨域訪問才行。
網上找了一下,發現通常有兩種方式。
1.在webapi路由裏面配置,EnableCorsAttribute 屬性進行配置。
2.在web.config 裏面配置。
在webapi 的apicontroller 裏面增加函數:
public class SearchApiController : ApiController
{//
IDALPage dalpage;
public SearchApiController()
{
dalpage = new DALPage();
}
//ajax 跨域訪問必須函數
public string Options()
{
return null; // HTTP 200 response with empty body
}
........
}
直接返回null。
- webapi 路由中配置,需要引用 Microsoft.AspNet.Cors,通過NuGet 進行獲取。
- 引用Microsoft.AspNet.Cors 完成之後,
- 修改webapi 路由代碼:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { //跨域配置 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
new EnableCorsAttribute("*", "*", "*") 可以根據需要改成web.config 裏面配置的值。
public static void Register(HttpConfiguration config) { //跨域配置 // config.EnableCors(new EnableCorsAttribute("*", "*", "*")); //跨域配置 var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"]; var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"]; var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"]; var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods) { SupportsCredentials = true }; config.EnableCors(geduCors); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); }
- 修改Global Application_Start 中的註冊webapi 路由的代碼:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// WebApiConfig.Register(GlobalConfiguration.Configuration);//原代碼
GlobalConfiguration.Configure(WebApiConfig.Register);//修改後。
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
以上配置及代碼在調試中使用沒有問題,可以實現ajax 跨域請求。即 使用vs自帶的IIS Express 運行。但發佈到IIS 正式環境上後,發現ajax 跨域請求不成功。
2. 部署到IIS 正式環境的配置, 直接在web.config 中配置跨域請求參數
注意:需要屏蔽webapi 路由配置的代碼。// config.EnableCors(....)
在web.config 的<system.webServer>節點裏面增加一下配置:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
上述爲個人遇到的情況及解決方式。如果您有更好的方式,歡迎留言,大家一起探討一下。