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. PHP 根据IP地址获取所在城市

    header('Content-Type:text/html;Charset=utf-8'); function GetIp(){ $realip = ''; $unknown = 'unknown' ...

  2. 在使用Vue.js中使用axios库时,遇到415错误(不支持的媒体类型(Unsupported media type))

    知识点:vue2.0中使用axios进行(put,post请求时),遇到415错误 解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'applicati ...

  3. Matrix_QP(A_2SeqSum)

    hdu_4686 题目大意:给出an,bn的递推,求ai*bi(i=0,1,--n-1)的和(an=a(n-1)*Ax+Ay, bn=b(n-1)*Bx+By, a0=A0, b0=B0, Ax,Bx ...

  4. zpar使用方法之Chinese Word Segmentation

    第一步在这里: http://people.sutd.edu.sg/~yue_zhang/doc/doc/qs.html 你可以找到这句话, 所以在命令行中分别敲入 make zpar make zp ...

  5. 手把手教你整合 SpringMvc+Spring+MyBatis+Maven

    注:该教程是参考孙宇老师的<SpringMvc+Spring+Mybatis+Maven整合视频教程1>整理的,花了我六个多小时,边复习视频边调代码边写教程,保证该教程每一步都能正确执行, ...

  6. ubuntu install git vim Plug manage

    在UBUNTU采用163或是阿里云来更新源,最新的更新源地址可以在网上查阅, 阿里源 deb http://mirrors.aliyun.com/ubuntu/ bionic main restric ...

  7. raid1磁盘更换---测试

    安装centos6.71. CentOS安装过程配raid.参考:http://www.360doc.com/content/13/1209/21/14661619_335823338.shtml. ...

  8. Solr学习总结 Solr的安装与配置

    接着前一篇,这里总结下Solr的安装与配置 1.准备 1.安装Java8 和 Tomcat9 ,java和tomcat 的安装这里不再重复.需要注意的是这两个的版本兼容问题.貌似java8 不支持,t ...

  9. 从源码角度分析 Kotlin by lazy 的实现

    by lazy 的作用 延迟属性(lazy properties) 是 Kotlin 标准库中的标准委托之一,可以通过 by lazy 来实现. 其中,lazy() 是一个函数,可以接受一个 Lamb ...

  10. bootstrap 知识点

    1.datetimepicker //带分钟选择 $('.form_datetime').datetimepicker({ format: 'yyyy-mm-dd HH:mm:ss', languag ...