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

posted @ 2019-03-16 15:40  WebApi  阅读(1276)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI