zoukankan      html  css  js  c++  java
  • Asp.Net WebApi 跨域设置

    跨越问题主要发生在客户端ajax请求时,为了安全设置,默认webapi是不允许ajax跨越请求的,不过有方法设置让支持跨越,我说说最常见的两种方法

    一、jquery jsonp

    缺点:JSONP也有局限性,只能针对于Get请求不能用于POST请求

    1、新建过滤器

    Filters/JsonCallbackAttribute.cs

    using System.Net.Http;
    using System.Text;
    using System.Web.Http.Filters;
    
    namespace cms.Web
    {
        public class JsonCallbackAttribute : ActionFilterAttribute
        {
            private const string CallbackQueryParameter = "jsoncallback";
    
            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());
                }
    
                base.OnActionExecuted(context);
            }
    
            private bool IsJsonp(out string callback)
            {
                callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter];
    
                return !string.IsNullOrEmpty(callback);
            }
        }
    }

    2、Global.asax注册

    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());//让webapi支持jsonp跨越请求
    }

    3、webapi

    api方法地址:www.ceshi1.com/api/ceshi/getceshi

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Http.Results;
    using cms.BLL;
    using cms.Model;
    
    namespace cms.Web.API
    {
        public class CeshiController : ApiController
        {
            public IHttpActionResult GetCeshi()
            {
                dynamic data = new { status = true, message = "webapi success" };
                return Json<dynamic>(data);
            }
        }
    }

    4、ceshi.html

    访问地址:www.ceshi2.com/ceshi.html

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="/js/jquery.js"></script>
    </head>
    <body>
        测试结果1:<span id="test" style="color:Red"></span><br />
        测试结果2:<span id="test2" style="color:Red"></span>
        <script type="text/javascript">
            function success_jsonpCallback(data) {
                alert(data)
            }
            $(function () {
                $.getJSON("http://www.ceshi1.com/api/ceshi/Getceshi?jsoncallback=?",
                    function (data) {
                        $("#test").html(data.message);
                    }
                );
                $.ajax({
                    type: "get",
                    url: "http://www.ceshi1.com/api/ceshi/Getceshi",
                    dataType: "jsonp",
                    jsonp: "jsoncallback",
                    //async: false,
                    success: function (data) {
                        $("#test2").html(data.message);
                    },
                    error: function (e) {
                        $("#test2").html("Error");
                    }
                });
                
            });
        </script>
    </body>
    </html>

    二、webapi.cors

    CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
    它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

    推荐使用这个解决跨越问题

    1、安装webapi.cors

    2、配置WebApiConfig

    using System;
    using System.Collections.Generic;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace WebApi
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API 配置和服务
    
    
                //设置cors允许跨越
                config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
    
    
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }

    3、webapi

    api方法地址:www.ceshi1.com/api/ceshi/getceshi

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace WebApi.Controllers
    {
        //自定义cors
        //[EnableCors(origins: "http://www.ceshi2.com", headers: "*", methods: "*")]
        //[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")]
        public class CeshiController : ApiController
        {
            public IHttpActionResult GetCeshi()
            {
                dynamic data = new { status = true, message = "webapi success" };
                return Json<dynamic>(data);
            }
        }
    }

    4、ceshi.html

    访问地址:www.ceshi2.com/ceshi.html

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="/js/jquery.js"></script>
    </head>
    <body>
        测试结果1:<span id="test" style="color:Red"></span><br />
        测试结果2:<span id="test2" style="color:Red"></span>
        <script type="text/javascript">
            $(function () {
                $.get("http://1.ceshi.com/api/ceshi/Getceshi",
                    function (data) {
                        $("#test").html(data.message);
                    }
                );
                jQuery.support.cors = true;//必须,不然ie8、ie9不支持跨越
                $.ajax({
                    type: "get",
                    url: "http://1.ceshi.com/api/ceshi/Getceshi",
                    //dataType: "json",
                    success: function (data) {
                        $("#test2").html(data.message);
                    },
                    error: function (e) {
                        $("#test2").html("Error");
                    }
                });
                
            });
        </script>
    </body>
    </html>

    说明:cors设置后ajax就和普通写法一样调用了

    注意:刚开始我的webapi和mvc在一个项目中,设置cors不起作用,不知道为何。然后把webapi单独一个项目却可以,坑死我了。

    end

  • 相关阅读:
    jstl标签的fmt:formatDate格式化日期 String to Date
    Spring MVC使用ModelAndView进行重定向
    配置SpringAop时需要用到的AspectJ表达式
    深入分析Java Web中的编码问题
    第六十五条:不要忽略异常
    第六十四条:努力使失败保持原子性
    第六十三条:在细节消息中包含能捕获失败的信息
    第六十二条:每个方法抛出的异常都要有文档
    第六十一条:抛出与抽象相对应的异常
    第六十条:优先使用标准的异常
  • 原文地址:https://www.cnblogs.com/webapi/p/10542547.html
Copyright © 2011-2022 走看看