ASP.NET MVC 定义JsonpResult实现跨域请求
1:原理
在js中,XMLHttpRequest是不能请求不同域的数据,但是script标签却可以,所以可以用script标签实现跨域请求。具体是定义一个函数,例如jsonp1234,请求不同域的url时带上函数名,例如:http://otherdomain.com/index?callback=jsonp1234,然后服务端根据callback获取这个函数名,然后传入json字符串作为函数参数。
2:实现
http://localhost:62203/home/index页面代码如下
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
function showMessage(result) {
alert(result.name)
}
</script>
<script src="http://localhost:16308/home/index?callback=showMessage" type="text/javascript"></script>
</head>
<body>
<div>
</div>
</body>
</html>
主要是这句
<script src="http://localhost:16308/home/index?callback=showMessage" type="text/javascript"></script>,
可以看到,访问的是不同的站点,并且callback的参数值为showMessage,
http://localhost:16308/home/index代码如下
public ActionResult Index()
{
string callback = this.Request["callback"];
string json="{\"name\":\"server\"}";
this.Response.Write(callback + "(" + json + ")");
return new EmptyResult();
}
根据callback获取函数名,然后将json字符串作为函数参数。
访问页面http://localhost:62203/home/index,效果如下
可见,站点localhost:62203从站点localhost:16308获取到了数据。
但是我们看服务端的实现,这也太不美观,也比较麻烦。
public ActionResult Index()
{
string callback = this.Request["callback"];
string json="{\"name\":\"server\"}";
this.Response.Write(callback + "(" + json + ")");
return new EmptyResult();
}
我们想要的是调用一个方法,就能实现跨域了,那如何实现呢。看到Controller有个this.Json方法,类型是JsonResult,我们可以参考这个类。定义一个类JsonpResult,派生于JsonResult,在ExecuteResult方法根据callback获取函数名,然后传入json字符串作为函数参数。
public class JsonpResult : JsonResult
{
public static readonly string JsonpCallbackName = "callback";
public static readonly string CallbackApplicationType = "application/json"; public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
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));//首先根据callback获取获取函数名,然后传入json字符串作为函数参数
else
buffer = serializer.Serialize(Data);
response.Write(buffer);
}
}
}
JsonpResult类有了,但是想在Controller这样使用this.Jsonp,所以为Controller类定义一个扩展方法,
public static class ControllerExtension
{
public static JsonpResult Jsonp(this Controller controller, object data)
{
JsonpResult result = new JsonpResult()
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return result;
}
}
这是在Controller就可以直接使用this.Jsonp了,把跨域服务端的代码改下
public ActionResult Index()
{
return this.Jsonp(new { name = "server JsonpResult" });
}
相比上面那个简洁多了
再次打开http://localhost:62203/home/index

同样,站点localhost:62203从站点localhost:16308获取到了数据,和上面的一样
ASP.NET MVC 定义JsonpResult实现跨域请求的更多相关文章
- MVC 定义JsonpResult实现跨域请求
MVC 定义JsonpResult实现跨域请求 1:原理 在js中,XMLHttpRequest是不能请求不同域的数据,但是script标签却可以,所以可以用script标签实现跨域请求.具体是定义一 ...
- spring mvc \ spring boot 允许跨域请求 配置类
用@Component 注释下,随便放个地方就可以了 package com.chinaws.wsarchivesserver.core.config; import org.springframew ...
- asp.net mvc 安全测试漏洞 "跨站点请求伪造" 问题解决
IBM Security Appscan漏洞筛查-跨站请求伪造,该漏洞的产生,有多种情况: 1.WebApi的跨站请求伪造,需要对WebApi的请求头部做限制(此文不做详细介绍): 2.MVC Act ...
- asp.net mvc web api 可跨域方法
1.直接修改 web.config ,不过这是针对所有 Action. <location path="Sample.txt"> <system.webServe ...
- ASP.NET Core 利用中间件支持跨域请求
方法1: 在Startup的ConfigureServices()中添加services.AddCors()在Startup的Configure()中添加app.UseCors(); 保证其在app. ...
- ASP.NET MVC 实现AJAX跨域请求方法《1》
ASP.NET MVC 实现AJAX跨域请求的两种方法 通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据 ...
- ASP.NET MVC 实现AJAX跨域请求的两种方法
通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据的加载,例如Google. 在ASP.NET MVC 框 ...
- ASP.NET MVC 实现 AJAX 跨域请求
ASP.NET MVC 实现AJAX跨域请求的两种方法 和大家分享下Ajax 跨域的经验,之前也找了好多资料,但是都不行,后来看到个可行的修改了并测试下 果然OK了 希望对大家有所帮助! 通常发送 ...
- 解决ajax跨域请求问题
自己做网站的时候,经常遇到跨域问题,下面是平时多次实践总结出的解决方法,大家有什么更好的思路,可以相互交流下~ XMLHttpRequest cannot load http://www.imooc. ...
随机推荐
- c盘没有新建修改权限的,执行下面命令
cmd中执行: icacls c:\ /setintegritylevel M
- C# Excel操作类
/// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...
- 创建maven项目出现的问题
右击项目无法显示maven图标,创建的pom.xml无法识别,并且创建maven项目时,一直显示Loading archetype list...
- thinkphp xml编码函数
/** * XML编码 * @param mixed $data 数据 * @param string $root 根节点名 * @param string $item 数字索引的子节点名 * @pa ...
- C# 数组排序 基本算法 分类: C# 2014-09-25 15:43 129人阅读 评论(0) 收藏
说明:冒泡.直接插入.选择.自带方法四中基本排序算法. using System; using System.Collections.Generic; using System.ComponentMo ...
- css3实践—创建3D立方体
css3实践-创建3D立方体 要想实现3D的效果,其实非常简单,只需指定一个元素为容器并设置transform-style:preserve-3d,那么它的后代元素便会有3D效果.不过有很多需要注意的 ...
- HDU2699+Easy
简单题. /* */ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<alg ...
- Building Tomcat7 source step by step---官方文档
Table of Contents Introduction Download a Java Development Kit (JDK) version 6 Install Apache Ant 1. ...
- python-字典(第二篇(四):字典)
[Python之旅]第二篇(四):字典 摘要: 说明: 显然Python中字典的学习过程与列表是一样的,主要是围绕下面的函数来进行重点学习: 1 2 3 4 5 6 7 8 9 10 11 & ...
- ASP.NET 打包下载文件
使用的类库为:ICSharpCode.SharpZipLib.dll 一种是打包整个文件夹,另一种是打包指定的多个文件,大同小异: using ICSharpCode.SharpZipLib.Zip; ...
