• 周三. 4月 24th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问。

admin

11月 28, 2021

由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题。

刚开始没做任何处理,用jsonp的方式调用 web api 接口,总是报一个错误,如下:

如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的:

{"YourSignature":"嫁人要嫁程序员,钱多话少死得早"}

 然而,JSONP请求期望得到这样的JSON:

jQuery123456([{"YourSignature":"嫁人要嫁程序员,钱多话少死得早"}])

所以我们需要对WebAPI做拓展,让它支持这样的callback

解决方案如下:

只需要给全局注册一个JsonCallbackAttribute,就可以判断接口的访问是属于跨域,还是非跨域,正常的返回。

因为我们的接口,可能是用来给 移动端(Android 、IOS)做数据接口,也有可能是给网站用,所以,考虑到可能存在跨域的问题。

   GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
 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());
                //context.Response.Content = new StringContent("C("a")");
            }

            base.OnActionExecuted(context);
        }

        private bool IsJsonp(out string callback)
        {
            callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter];

            return !string.IsNullOrEmpty(callback);
        }

结合下面图片不难开出,请求的地址带回了,callback的参数标识。

 

 测试代码如下:

<html>
<head>
    <title>团队信息列表</title>
    <script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.js")"></script>
</head>
<body>
    <ul id="contacts"></ul>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                Type: "GET",
                url: "http://app.uni2uni.com/api/CloudService/GetAllGroup",
                dataType: "jsonp",
                success: listContacts
            });
        });

        function listContacts(contacts) {
            alert(contacts);
            $.each(contacts.data, function (index, contact) {
                var html = "<li><ul>";
                html += "<li>GroupName: " + contact.GroupName + "</li>";
                html += "<li>GroupPicture:" + contact.GroupPicture + "</li>";
                html += "</ul>";
                $("#contacts").append($(html));
            });
        }
    </script>
</body>
</html>

返回接口如下:

相关文章推荐:http://diaosbook.com/Post/2013/12/27/tips-for-aspnet-webapi-cors

《如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问。》有一个想法

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注