MVC4 WebApi 跨域问题

 1 只需要给全局注册一个JsonCallbackAttribute,就可以判断接口的访问是属于跨域,还是非跨域,正常的返回。
 2 
 3 因为我们的接口,可能是用来给 移动端(Android 、IOS)做数据接口,也有可能是给网站用,所以,考虑到可能存在跨域的问题
 4 
 5 GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
 6 
 7  public class JsonCallbackAttribute : ActionFilterAttribute
 8     {
 9         private const string CallbackQueryParameter = "callback";
10 
11         public override void OnActionExecuted(HttpActionExecutedContext context)
12         {
13             var callback = string.Empty;
14 
15             if (IsJsonp(out callback))
16             {
17                 var jsonBuilder = new StringBuilder(callback);
18 
19                 jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
20 
21                 context.Response.Content = new StringContent(jsonBuilder.ToString());
22                 //context.Response.Content = new StringContent("C(\"a\")");
23             }
24 
25             base.OnActionExecuted(context);
26         }
27 
28         private bool IsJsonp(out string callback)
29         {
30             callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter];
31 
32             return !string.IsNullOrEmpty(callback);
33         }
34 
35 请求的地址带回了,callback的参数标识。

 

posted @ 2015-01-20 14:03  以沫浅夏  阅读(405)  评论(0编辑  收藏  举报