asp.net webapi 跨域訪問 在vs除錯裡面和部署到IIS裡面的配置問題
阿新 • • 發佈:2018-12-12
最近在寫個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>
上述為個人遇到的情況及解決方式。如果您有更好的方式,歡迎留言,大家一起探討一下。