ASP.NET Web API 启用跨域访问
自定义特性
要在WebApi中实现JSONP,一种方式是实现自定义特性 http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/
public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext context) { var callback = string.Empty; if (IsJsonp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result); context.Response.Content = new StringContent(jsonBuilder.ToString()); } base.OnActionExecuted(context); } private bool IsJsonp(out string callback) { callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); } }
后面只需要在需要支持JSONP的方法上加上JsonCallback特性即可。
自定义JsonMediaTypeFormatter
大A的文章:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html
WebApiContrib.Formatting.Jsonp
https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Install-Package
WebApiContrib.Formatting.Jsonp
修改Global.asax.cs文件
protected void Application_Start() { //add jsonp GlobalConfiguration.Configuration.AddJsonpFormatter(); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
需要支持jsonP的方法都加上callback参数即可
public IEnumerable<User> NextPage(int id, string callback = "")
官方的方式
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Install-Package Microsoft.AspNet.WebApi.Cors
修改WebApiConfig.Register启用JSONP
config.EnableCors();
在Controller上加上Attribute
[EnableCors(origins: http://jsonpapi.xxxx.net, headers: "*", methods: "*")]
检查防火墙启用了 OPTIONS类型的请求 请求,这个问题找了我好久
REFER:
http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api
http://edi.wang/post/2013/12/27/tips-for-aspnet-webapi-cors
分类:
ASP.NET WebAPI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述