在Web Api中快速实现JSonp

本文翻译自:http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started

Concept:

同源策略:同源策略是客户端语言中的一个概念,它允许元素获取同一个站点中的资源,请求别的domain中的资源将不会被允许。

跨域资源共享[Cross-origin resource sharing (CORS)]:指的是我们可以通过javascript的Ajax(XMLHttpRequests)请求去访问其他的domain,这种请求通常会被浏览器拒绝,但是我们可以通过一些方法来时的浏览器允许这项操作,我们称之为CORS。

JSONP:由于安全问题,浏览器不允许跨域的Ajax的实现,JSONP(JavaScript Object Notation with Padding )是一个从外部的域抓取JSON数据的方式,他会比其他的实现方式(web proxy and IFrame)更优雅。

JSONP (JavaScript Object Notation with Padding) = JSON data padded with JavaScript function name

更多关于JSONP的介绍:

http://www.codeproject.com/Articles/42641/JSON-to-JSONP-Bypass-Same-Origin-Policy

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

 

 

Implimentation:

1、创建两个项目:WebApi、WebApp,分别任是webapi、MVC项目;

2、在WebApi项目中(1-5均在此项目中),利用Nuget安装WebApiContrib.Formatting.Jsonp;

3、在App_Start文件夹添加FormatterConfig类,类的代码如下:

public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
{
    var jsonFormatter = formatters.JsonFormatter;
    jsonFormatter.SerializerSettings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    // Insert the JSONP formatter in front of the standard JSON formatter.
    var jsonpFormatter = new JsonpMediaTypeFormatter(formatters.JsonFormatter);
    formatters.Insert(0, jsonpFormatter);
}

4、在App_Start/WebApiConfig.cs中覆盖原来的路由为:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}/{format}",
    defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional }
);

 

5、在global文件中添加一条代码:

FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration.Formatters);

 

此时我们已经实现了JSONP了,现在我们来做一个测试:

 

6、在WebApi项目中的Controller文件夹中添加一个class,代码为:

namespace WebApi.Controllers
{
    public class ContactsController:ApiController
    {
       public IEnumerable<Contact> GetAllContacts()
        {
            Contact[] contacts = new Contact[]
            {
                new Contact{ Name="张三", PhoneNo="123", EmailAddress="zhangsan@gmail.com"},
                new Contact{ Name="李四", PhoneNo="456", EmailAddress="lisi@gmail.com"},
                new Contact{ Name="王五", PhoneNo="789", EmailAddress="wangwu@gmail.com"},
            };
            return contacts;
        }
    }

    public class Contact
    {
        public string Name { get; set; }
        public string PhoneNo { get; set; }
        public string EmailAddress { get; set; }
    }
}

 

 

7、在WebApp中的某个Action的View中代码为:

<html>
<head>
     <title>联系人列表</title>
     <script src="../../Scripts/jquery-1.7.1.js"></script>
</head>
<body>
     <ul id="contacts"></ul>
     <script type="text/javascript">
                     $(function ()
                     {
                         alert("");
                                 $.ajax({
                                         Type       : "GET",
                                         url        : "
http://localhost:57826/api/contacts",
                                         dataType   : "jsonp",
                                         success    : listContacts
                                 });
                         });
             
                     function listContacts(contacts) {
                         alert("");
                             $.each(contacts, function (index, contact) {
                                     var html = "<li><ul>";
                                     html += "<li>Name: " + contact.Name + "</li>";
                                     html += "<li>Phone No:" + contact.PhoneNo + "</li>";
                                     html += "<li>Email Address: " + contact.EmailAddress + "</li>";
                                     html += "</ul>";
                                     $("#contacts").append($(html));
                                 });
                         }
                 </script>
</body>
</html>

 

8、通过WebApp中的页面请求WebApi,最终显示的结果为:

Capture

posted on 2014-02-18 15:51  Creater  阅读(524)  评论(0编辑  收藏  举报

导航