How to make your Asp.Net Web Api interface embrace support cross-domain access.

As the web api project are usually made of a separate site, to provide the data, doing web api project, the front end can not help but encounter problems cross-domain access interface.

Beginning did not do any treatment, call the web api interfaces with jsonp way, always report an error, as follows:

If you want to use JSONP to obtain data across domains, WebAPI itself does not support the callback javascript, it returns JSON like this:

{ "YourSignature" : "marry marry programmer, then less money die early" }

 However, JSONP request expect this JSON:

jQuery123456 ([{ "YourSignature" : "marry marry programmer, then less money died early" }])

So we need to do WebAPI development, it supports the callback

 

 

Solutions are as follows:

Just to give a global registration JsonCallbackAttribute, you can determine the access interface is part of a cross-domain or cross-domain non-normal returns.

Because we interface may be used to move end (Android, IOS) for data interface it is also possible to use the site, so, taking into account the possible existence of cross-domain problems.

   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);
        }

The following combination is not difficult to picture out, back to the requested address, callback parameter identification.

 

 Test code is as follows:

<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>

Returns an interface as follows:

Recommended related articles: http: //diaosbook.com/Post/2013/12/27/tips-for-aspnet-webapi-cors

 

Reproduced in: https: //www.cnblogs.com/Kummy/p/3767269.html

Guess you like

Origin blog.csdn.net/weixin_34348805/article/details/93428279