zoukankan      html  css  js  c++  java
  • C#解决jsonp跨域问题jsonp跨域配置

    1,建立一个CorsHandler类

    public class CorsHandler : DelegatingHandler
    {
    const string Origin = "Origin";
    const string AccessControlRequestMethod = "Access-Control-Request-Method";
    const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
    const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
    const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
    const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
    bool isCorsRequest = request.Headers.Contains(Origin);
    bool isPreflightRequest = request.Method == HttpMethod.Options;
    if (isCorsRequest)
    {
    if (isPreflightRequest)
    {
    return Task.Factory.StartNew<HttpResponseMessage>(() =>
    {
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

    string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
    if (accessControlRequestMethod != null)
    {
    response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
    }

    string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
    if (!string.IsNullOrEmpty(requestedHeaders))
    {
    response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
    }

    return response;
    }, cancellationToken);
    }
    else
    {
    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
    {
    HttpResponseMessage resp = t.Result;
    resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
    return resp;
    });
    }
    }
    else
    {
    return base.SendAsync(request, cancellationToken);
    }
    }
    }

    2、在Application_Start()里面配置

    //jsonp跨域
    GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());

    OK,完美解决。

  • 相关阅读:
    ecshop里的$_CFG从哪来的
    高效PHP程序必知的53个技巧
    Jquery结合datagrid框架
    PHP数据类型转换(字符转数字,数字转字符)
    php 操作数组 (合并,拆分,追加,查找,删除等)
    css3制作导航栏
    php日期转时间戳,指定日期转换成时间戳
    PHP 时间与字符串的相互转化
    php 生成.txt文件
    linux PHP yum 安装phpzie
  • 原文地址:https://www.cnblogs.com/wjslw/p/5937438.html
Copyright © 2011-2022 走看看