ajax跨域系列--web api方式跨域

上一节讲到如何使用jsonp进行跨域请求api,这次我们用一些微软新的框架解决这个问题

web api是微软继web service ,wcf推出的新一代的服务提供框架

不多说了,用用看


首先一个基类,所有的controller继承此基类,里面有个无返回值的方法Options

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class ApiController : Controller
    {
        public string Options()
        {
            return null; // HTTP 200 response with empty body

        }
    }
}
我们的具体调用的action:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Filter;

namespace MvcApplication1.Controllers
{

    public class HomeController : ApiController
    {
        public ActionResult Index()
        {
            return View();
        }

       
        public JsonResult Get()
        {
            IList<DataModel> ls=new List<DataModel>(){
                new DataModel{
                    name="kong",
                    age=25
                },
                new DataModel{
                    name="wang",
                    age=26
                }
            };
            return Json(ls, JsonRequestBehavior.AllowGet);
        }
    }

    public class DataModel
    {
        public string name { get; set; }
        public int age { get; set; }
    }
}


在根目录下配置web.config里面的system.webServer节点,新增
<pre name="code" class="html"> <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
      </customHeaders>
    </httpProtocol>
-------------------------------------------以上是webapi项目下面是调用者的前端页面:
<pre name="code" class="javascript"><script type="text/javascript">
        $(function () {
            $.ajax({
                type: "get",
                async: false,
                url: "http://localhost:8/home/get",
                dataType: "json",
                success: function (json) {
                    var html = '<li class="swiper-slide tabNavActive">推荐</li>';
                    $.each(json, function () {
                        html += '<li class="swiper-slide">' + this.name + '</li>';
                    });
                    $("#floor").html(html);
                },
                error: function () {
                    alert('fail');
                }
            });
        });
    </script>
测试OK。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值