上一节讲到如何使用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。 原文链接:https://www.f2er.com/ajax/162331.html