Fork me on GitHub

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

posted @   花儿笑弯了腰  阅读(660)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 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的设计模式综述
点击右上角即可分享
微信分享提示