ajax 跨域问题

mvc 项目中需要在服务端webconfig 文件中添加

  <system.webServer>
    <!-- 这是防止跨域问题增加的代码  开始-->
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <!-- 这是防止跨域问题增加的代码  结束-->
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

  如果是web api 项目(JsonP方式请求数据)

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

解决方案如下:

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

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

<strong>   GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());</strong>
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);

}

  

原文地址:https://www.cnblogs.com/sdaulldd/p/4401536.html