JSONP可以帮我们解决跨域访问的问题。JSONP is JSON With Padding. 这里我们将不再解释其原理。我们来看在ASP.NET MVC 3 如何实现。首先我们需要定义一个JsonpResult. 代码像这样, 直接继承自JsonResult, override了ExecuteResult方法

public class JsonpResult : JsonResult
{
private static readonly string JsonpCallbackName = "callback";
private static readonly string CallbackApplicationType = "application/json"; /// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context within which the result is executed.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
{
throw new InvalidOperationException();
}
var response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = CallbackApplicationType;
if (ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (Data != null)
{
String buffer;
var request = context.HttpContext.Request;
var serializer = new JavaScriptSerializer();
if (request[JsonpCallbackName] != null)
buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
else
buffer = serializer.Serialize(Data);
response.Write(buffer);
}
}
}
接着简单定义一个扩展方法:
public static class ContollerExtensions
{
/// <summary>
/// Extension methods for the controller to allow jsonp.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="data">The data.</param>
/// <returns></returns>
public static JsonpResult Jsonp(this Controller controller, object data)
{
JsonpResult result = new JsonpResult()
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
}; return result;
}
}

在Controller里使用它, 我们的Controller叫ApiController,其中的Action:

/// <summary>
/// Get some basic information with a JSONP GET request.
/// </summary>
/// <remarks>
/// Sample url:
/// http://localhost:50211/Api/GetInformation?key=test&callback=json123123
/// </remarks>
/// <param name="key">key</param>
/// <returns>JsonpResult</returns>
public JsonpResult GetInformation(string key)
{
var resp = new Models.CustomObject();
if (ValidateKey(key))
{
resp.Data = "You provided key: " + key;
resp.Success = true;
}
else
{
resp.Message = "unauthorized";
} return this.Jsonp(resp);
} private bool ValidateKey(string key)
{
if (!string.IsNullOrEmpty(key))
return true;
return false;
}

上面的方法接收一个string的参数,接着我们在前面加一个前缀字符串,最后返回就是Jsonp Result.

传值的Model:

public class CustomObject
{
public bool Success { get; set; }
public object Data { get; set; }
public string Message { get; set; }
}

运行WebSite, 访问 http://localhost:50211/Api/GetInformation?callback=myfunction&key=haha

我们可以看到这样的结果:

myfunction({"Success":true,"Data":"You provided key: haha","Message":null})
 
好的,现在让我们在另一个站点里使用它:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.result').hide(); $('#test').click(function () {
$('.result').fadeOut('fast');
$('.result').html(''); $.ajax({
url: 'http://localhost:50211/Api/GetInformation',
data: { key: $('input[name=key]').val() },
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
});
}); function localJsonpCallback(json) {
//do stuff...
if (json.Success) {
$('.result').html(json.Data);
}
else {
$('.result').html(json.Message);
} $('.result').fadeIn('fast');
}
</script>
</head>
<body>
<div>
Enter key: <input type="text" name="key" value="some data key, this parameter is optional" />
<br /><input type="button" value="Test JSONP" id="test" />
<div class="result">
</div>
</div>
</body>
</html>

这里使用的JQuery的Ajax来调用它, 熟悉JQuery的应该能看懂, 结果是在button下div显示字符串:

You provided key: some data key, this parameter is optional

在这里,也可以使用getJSON方法。 
好了,就这么简单。希望对您Web开发有帮助。

摘自:http://www.cnblogs.com/wintersun/archive/2012/05/25/2518572.html

Asp.net MVC 实现JSONP的更多相关文章

  1. 主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP

    原文:主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP 原文地址 http://www.codeguru.com/csharp/.net/net_asp/using-jso ...

  2. 案例:1 Ionic Framework+AngularJS+ASP.NET MVC WebApi Jsonp 移动开发

    落叶的庭院扫的一干二净之后,还要轻轻把树摇一下,抖落几片叶子,这才是Wabi Sabi的境界. 介绍:Ionic是移动框架,angularjs这就不用说了,ASP.Net MVC WebApi提供数据 ...

  3. 让ASP.NET MVC不使用jsonp也可以跨域访问

    跨域问题仅仅发生在Javascript发起AJAX调用,或者Silverlight发起服务调用时,其根本原因是因为浏览器对于这两种请求,所给予的权限是较低的,通常只允许调用本域中的资源,除非目标服务器 ...

  4. Cordova+Asp.net Mvc+GIS跨平台移动应用开发实战1-系统初步搭建(附演示,apk,全部源码)

    1.前言 身处在移动互联网的今天,移动应用开发炙手可热,身为程序猿的我们怎么能错过开发一款我们自己的APP.本人算是一个基于.net的GIS开发入门者(马上就大四啦), 暑假在学校参加GIS比赛有大把 ...

  5. ASP.NET MVC 实现AJAX跨域请求方法《1》

    ASP.NET MVC 实现AJAX跨域请求的两种方法 通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据 ...

  6. ASP.NET MVC+EF在服务端分页使用jqGrid以及jquery Datatables的注意事项

    引言: 本人想自己个博客网站出来,技术路线是用ASN.NET MVC5+EF6(Code First)+ZUI+各种Jquery插件,有了这个想法之后就开始选择UI,看了好多bootstrap的模板之 ...

  7. ArcGIS Server 10.2 实战(一)Asp.net MVC与JSON数据妙用实现动态生成要素图层

    今年7月刚刚发布的ArcGIS 10.2为GIS的web开发带来了一个很实在的功能,JSON转要素.以往GIS图层外部数据(如文本数据,数据库数据)动态地写入地图服务中的图层是一件不可想象的事情,如今 ...

  8. Cordova+Asp.net Mvc+GIS

    Cordova+Asp.net Mvc+GIS跨平台移动应用开发实战1-系统初步搭建(附演示,apk,全部源码)   1.前言 身处在移动互联网的今天,移动应用开发炙手可热,身为程序猿的我们怎么能错过 ...

  9. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API

    原文:返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API [索引页][源码下载] 返璞归真 asp.net mvc (10) - asp.net ...

随机推荐

  1. vue.js的一些事件绑定和表单数据双向绑定

    知识点: v-on:相当于: 例如:v-on:click==@click ,menthods事件绑定 v-on修饰符可以指定键盘事件 v-model进行表单数据的双向绑定 <template&g ...

  2. spring boot 集成kafka (多线程,消费者使用kafka的原生api实现,因为@KakfkaListener修改groupId无效)

    application-test.properties #kafka kafka.consumer.zookeeper.connect=*:2181 kafka.consumer.servers=*: ...

  3. 爬虫框架Scrapy之案例二

    新浪网分类资讯爬虫 爬取新浪网导航页所有下所有大类.小类.小类里的子链接,以及子链接页面的新闻内容. 效果演示图: items.py import scrapy import sys reload(s ...

  4. CentOS7下安装VLC

    用最新的CentOS7发现没有视频播放器,于是在http://pkgs.org/上查找,发现了nux dextop仓库上有,于是到他的官网上http://li.nux.ro/repos.html查了下 ...

  5. 【分类】AlexNet论文总结

    目录 0. 论文链接 1. 概述 2. 对数据集的处理 3. 网络模型 3.1 ReLU Nonlinearity 3.2 Training on multiple GPUs 3.3 Local Re ...

  6. Objective C NSString 编码成URL 特殊字符处理

    找了一下网上的教程都是使用类似以下代码,Xcode提示这个CoreFoundation不受ARC管理,所以折中的方式是添加__bridge. NSString *encodedValue = (__b ...

  7. ADO.NET 使用DELETE语句批量删除操作,提示超时,删除失败,几种优化解决思路

    起因是如此简单的一句sql 提示:Timeout 时间已到.在操作完成之前超时时间已过或服务器未响应. 提供几种解决思路: 1.检查WHERE条件中字段是否已建索引 2.检查是否被其他表引用,引用表外 ...

  8. Linux 实用操作命令

    1. ssh远程连接服务器命令 ssh [username@]hostname 2. 查看远程服务器近期登陆记录 last 3. 用户及其主目录的创建 1.  useradd –d /home/lb ...

  9. Asp.net WebApi 配置 Swagger UI

    首先安装Swashbuckle.Core 然后添加swagger配置文件. [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), &q ...

  10. python 这个stdin怎么写

    !/usr/bin/env python -- coding: utf-8 -- import json import pprint import sys reload(sys) sys.setdef ...