zoukankan      html  css  js  c++  java
  • 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);
    
    }
    

      

  • 相关阅读:
    mysql学习笔记——建表需满足的三大范式
    mysql学习笔记——对数据记录查询操作的补充(单表内查询)
    mysql学习笔记——对数据表中记录的操作
    转载----- mysql 五大约束
    mysql笔记------对数据表操作
    c语言中static的用法
    解决Android抽屉被击穿问题
    解决ScrollView与ListView事件冲突
    使用Loader实时查询本地数据库用法
    Android中实现两次点击返回键退出本程序
  • 原文地址:https://www.cnblogs.com/sdaulldd/p/4401536.html
Copyright © 2011-2022 走看看