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. rsync | scp文件同步命令使用

    现在有一台服务器A,目录/data2/abc下存在若干文件夹和文件,需要复制到服务器B中.这时,可以在服务器A上执行rsync或者scp命令,将文件夹或文件复制到服务器B中. SCP: scp /da ...

  2. OpenDayLight "Error executing command: java.lang.NullPointerException"问题解决

    参考: Fedora 21 mostly working but NullPointerException at Karaf shell 在使用ODL的时候,安装功能组件时出现: Error exec ...

  3. Spring 集成rabbiatmq

    pom 文件 <dependencies> <dependency> <groupId>com.rabbitmq</groupId> <artif ...

  4. 简单易用的分页类实例代码PHP

    <?php /*********************************************** * @类名: page * @参数: $myde_total - 总记录数 * $m ...

  5. synchornized实现原理

    synchronized是基于Monitor来实现同步的. Monitor 的工作机理: 线程进入同步方法中. 为了继续执行临界区代码,线程必须获取 Monitor 锁.如果获取锁成功,将成为该监视者 ...

  6. 手机APP测试环境搭建---appium

    这些都不是重点---一切都可以参考虫师   Appium移动自动化测试(一)--安装Appium 1.ADB的安装:ADB(ANDROID DEBUG BRIDGE) 应用场景: 针对移动端 Andr ...

  7. jQuery 获取、设置表单元素的值

    获取表单元素值: 文本框,文本区域: $("#txt").attr("value"): 多选框 checkbox:$("#checkbox_id&qu ...

  8. StringUtils.isNumeric()的特殊点

    String str = "-1"; StringUtils.isNumeric(str) 返回的是false StringUtils.isNumeric()方法在判断字符串是否是 ...

  9. bzoj1083: [SCOI2005]繁忙的都市 瓶颈生成树

    https://www.lydsy.com/JudgeOnline/problem.php?id=1083 题意:给你一个图,求生成树最大边权最小值 就是求瓶颈生成树(生成树中最大边权最小),最小生成 ...

  10. 《深入理解mybatis原理4》 MyBatis缓存机制的设计与实现

    <深入理解mybatis原理> MyBatis缓存机制的设计与实现 本文主要讲解MyBatis非常棒的缓存机制的设计原理,给读者们介绍一下MyBatis的缓存机制的轮廓,然后会分别针对缓存 ...