Asp.net MVC 实现JSONP
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的更多相关文章
- 主攻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 ...
- 案例:1 Ionic Framework+AngularJS+ASP.NET MVC WebApi Jsonp 移动开发
落叶的庭院扫的一干二净之后,还要轻轻把树摇一下,抖落几片叶子,这才是Wabi Sabi的境界. 介绍:Ionic是移动框架,angularjs这就不用说了,ASP.Net MVC WebApi提供数据 ...
- 让ASP.NET MVC不使用jsonp也可以跨域访问
跨域问题仅仅发生在Javascript发起AJAX调用,或者Silverlight发起服务调用时,其根本原因是因为浏览器对于这两种请求,所给予的权限是较低的,通常只允许调用本域中的资源,除非目标服务器 ...
- Cordova+Asp.net Mvc+GIS跨平台移动应用开发实战1-系统初步搭建(附演示,apk,全部源码)
1.前言 身处在移动互联网的今天,移动应用开发炙手可热,身为程序猿的我们怎么能错过开发一款我们自己的APP.本人算是一个基于.net的GIS开发入门者(马上就大四啦), 暑假在学校参加GIS比赛有大把 ...
- ASP.NET MVC 实现AJAX跨域请求方法《1》
ASP.NET MVC 实现AJAX跨域请求的两种方法 通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据 ...
- ASP.NET MVC+EF在服务端分页使用jqGrid以及jquery Datatables的注意事项
引言: 本人想自己个博客网站出来,技术路线是用ASN.NET MVC5+EF6(Code First)+ZUI+各种Jquery插件,有了这个想法之后就开始选择UI,看了好多bootstrap的模板之 ...
- ArcGIS Server 10.2 实战(一)Asp.net MVC与JSON数据妙用实现动态生成要素图层
今年7月刚刚发布的ArcGIS 10.2为GIS的web开发带来了一个很实在的功能,JSON转要素.以往GIS图层外部数据(如文本数据,数据库数据)动态地写入地图服务中的图层是一件不可想象的事情,如今 ...
- Cordova+Asp.net Mvc+GIS
Cordova+Asp.net Mvc+GIS跨平台移动应用开发实战1-系统初步搭建(附演示,apk,全部源码) 1.前言 身处在移动互联网的今天,移动应用开发炙手可热,身为程序猿的我们怎么能错过 ...
- 返璞归真 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 ...
随机推荐
- java入门了解01
http://www.oracle.com/technetwork/java/javase/downloads/index.html dos命令大全:http://www.zou114.com/dos ...
- Putting Apache Kafka To Use: A Practical Guide to Building a Stream Data Platform-part 1
转自: http://www.confluent.io/blog/stream-data-platform-1/ These days you hear a lot about "strea ...
- 程序员清理xcode垃圾命令
xcrun simctl list devices xcrun simctl delete unavailable
- 8.scala:特质
版权申明:转载请注明出处.文章来源:http://bigdataer.net/?p=317 总体来说,scala中的特质类似于Java中的接口,但是有别于接口的是特质中既可以有实现方法也可以有抽象方法 ...
- 08_MySQL DQL_SQL99标准中的多表查询(内连接)
# sql99语法/*语法: select 查询列表 from 表1 别名 [连接类型] join 表2 别名 on 连接条件 [where 筛选条件] [group by 分组] [having 分 ...
- POJ 1144 Network(无向图的割顶和桥模板题)
http://poj.org/problem?id=1144 题意: 给出图,求割点数. 思路: 关于无向图的割顶和桥,这篇博客写的挺不错,有不懂的可以去看一下http://blog.csdn.net ...
- Elasticsearch 使用技巧笔记
1.重新分片 当出现Unassigned分片时,我们可以通过分片重分配解决这个问题 curl -X PUT http://192.168.0.37:9200/_cluster/settings \ - ...
- C# 过滤HTML,脚本,数据库关键字,特殊字符
/// <summary> /// 过滤标记 /// </summary> /// <param name="NoHTML">包括HTML,脚本 ...
- Android Studio 3.0 及个版本下载和 gradle 各版本下载
Android Studio 3.0 下载地址: 链接:http://pan.baidu.com/s/1jHVuOQi 密码:3pd0 Android Studio 3.0 包含了三大主要功能: 一套 ...
- Android----- 改变图标原有颜色 和 搜索框
本博客主要讲以下两点知识点 图标改变颜色:Drawable的变色,让Android也能有iOS那么方便的图片色调转换,就像同一个图标,但是有多个地方使用,并且颜色不一样,就可以用这个方法了. 搜索框: ...