ASP MVC 和 jsonp

发布于 2024-11-04 18:53:17 字数 750 浏览 1 评论 0原文

我需要通过 MVC 应用程序的 Jsonp 响应发送一些数据。对于 Jsonp 响应方法,我使用了 JsonpFilter。

这是我的 Jsonp 响应方法:

[JsonpFilter]
    public JsonResult GetPageName()
    {
        return new JsonResult
        {
            Data = Session["Page"],
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

这是 javascript 函数:

$.ajax({
            type: "GET",
            dataType: "jsonp",
            url: 'http://localhost:54845/Login/GetPageName',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data.width + "-" + data.height);
            }
        });

此代码仅在 FF 上运行良好。在 IE 中什么也没有发生。

我的代码有什么问题?谢谢。

I need to send some data through a Jsonp response from a MVC application. For Jsonp response method i used a JsonpFilter.

This is my Jsonp response method:

[JsonpFilter]
    public JsonResult GetPageName()
    {
        return new JsonResult
        {
            Data = Session["Page"],
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

and this is the javascript function:

$.ajax({
            type: "GET",
            dataType: "jsonp",
            url: 'http://localhost:54845/Login/GetPageName',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data.width + "-" + data.height);
            }
        });

This code works great only on FF. In IE nothing is happening.

What is wrong in my code? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

瑾夏年华 2024-11-11 18:53:17

您真的打算对 JSON 数据进行跨域 HTTP GET 吗?如果不是,为什么还要使用 JSONP?只需使用 JSON 即可。

Are you actually planning on making cross-domain HTTP GETs of JSON data? If not, why bother with JSONP? Just use JSON.

淡忘如思 2024-11-11 18:53:17

Firefox 正在变得松散。其他浏览器都是正经的家伙。

请参阅:在本地主机上运行时不执行 JSONP 回调

引用:

一个网站可以只通过
端口列表并继续调用
不同端口上的本地主机和
路径。 “Localhost”是少数几个 DNS 之一
含义动态的主机名
取决于时间和地点
询问,制定潜在目标
易受伤害的。是的,事实是
将点 (.) 附加到“localhost”
('localhost.') 产生一个工作
解决方法确实暴露了安全性
漏洞,但确实提供了
[暂定] 开发解决方法
目的。

更好的方法是绘制地图
环回 IP 到新的主机名条目
主机文件,使其正常工作
在本地,不容易被“修复”
浏览器更新了,但不起作用
除了开发之外的其他任何地方
工作站。

Firefox is being loosey goosey. The other browsers are being prude dudes.

See: JSONP callback doesn't execute when running at localhost

To quote:

A web site could just go through a
list of ports and keep invoking
localhost on different ports and
paths. 'Localhost' is one of few DNS
hostnames that are dynamic in meaning
depending on when and where it's
queried, making the potential targets
vulnerable. And yes, the fact that
appending a dot (.) to 'localhost'
('localhost.') produces a working
workaround does expose a security
vulnerability, but does offer a
[tentative] workaround for development
puposes.

A better approach is to map the
loopback IP to a new hostname entry in
the hosts file so that it works
locally, isn't prone to be "fixed" by
a browser update, and doesn't work
anywhere else but on the development
workstation.

耳钉梦 2024-11-11 18:53:17

问题出在 IE 会话变量上。
如果我用 new {var1 = "var1", var2 = "var2"} 替换 Session["Page"] ,它就可以工作。
所以我需要找到一个解决方案。
谢谢大家。

The problem is with IE session variables.
If i replace Session["Page"] with new {var1 = "var1", var2 = "var2"} it works.
So i need to find a solution for that.
Thank you all.

厌倦 2024-11-11 18:53:17

MVC / JSONP / DataSet 绑定

通过修改上面的代码,我能够让 JSONP 与 MVC 一起使用。此示例通过 JSONP 直接将数据集绑定到 html 元素。

控制器

>

公共类 HomeController :控制器
{
[http获取]
公共 ActionResult HeaderJSONP()
{
DsPromotion.HeaderDataTable tbl = new DsPromotion.HeaderDataTable();
DsPromotion.HeaderRow 行 = tbl.NewHeaderRow();
row.imgBanner_src = "/Content/Home/Image/MainBanner.gif";
tbl.Rows.Add(行);
返回新的 JsonpResult { 数据 = tbl };
}
}

结果

> public class JsonpResult : System.Web.Mvc.JsonResult
>    {
>        public override void ExecuteResult(ControllerContext context)
>        {
>            this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
>            if (context == null)
>            {
>                throw new ArgumentNullException("context");
>            }
>
>            HttpResponseBase response = context.HttpContext.Response;
>            if (!String.IsNullOrEmpty(ContentType))
>            {
>                response.ContentType = ContentType;
>            }
>            else
>            {
>                response.ContentType = "application/json";
>            }
>            if (ContentEncoding != null)
>            {
>                response.ContentEncoding = ContentEncoding;
>            }
>            if (Data != null)
>            {
>                HttpRequestBase request = context.HttpContext.Request;
>                JavaScriptSerializer jsonserializer = new JavaScriptSerializer();
>                DataTableConverter serializer = new DataTableConverter();
>                response.Write(request.Params["jsoncallback"] + "(" + jsonserializer.Serialize(serializer.Serialize(Data, new JavaScriptSerializer())) + ")");
>            }
>        }
>    }

Javascript / JQuery JSON 请求和回调

>

函数BindDataTable(dataTable) {
var 表名;
for (数据表中的表名) {
if (tableName.indexOf('') > 0) {
tableName = tableName.split('
')[0];
}
}
var 元素和Attrib;
for (elementAndAttrib in dataTable[tableName][0]) {
var elementID = elementAndAttrib.split('')[0];
var attribName = elementAndAttrib.split('
')[1];
var attribValue = dataTable[表名][0][elementAndAttrib];
$("#" + elementID).attr(attribName, attribValue);
}
}
函数 GetHomeHeaderCallBack(tblHeader) {
绑定数据表(tblHeader);
}
函数 GetHomeHeader() {
var call = "/Home/HeaderJSONP?jsoncallback=?&" + Math.round(new Date().getTime());
$.getJSON(call, { 格式: "json" }, GetHomeHeaderCallBack);
}
$(GetHomeHeader);

局部视图

<%@ 控制语言="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

XSD

...

表序列化器

>

公共类DataTableConverter:JavaScriptConverter
{
公共覆盖 IEnumerable SupportedTypes
{
get { return new Type[] { typeof(DataTable) }; }
}

 public override object Deserialize(IDictionarydictionary, Type type,
   JavaScriptSerializer 序列化器)
   {
       抛出新的NotImplementedException();
   }

   公共覆盖 IDictionary;序列化(对象 obj,JavaScriptSerializer 序列化器)
   {
       数据表列表类型 = obj 作为数据表;

       if (列表类型!= null)
       {
           // 创建表示。
           字典<字符串,对象>结果 = new Dictionary<字符串, 对象>();
           ArrayList itemsList = new ArrayList();
           foreach(listType.Rows 中的 DataRow 行)
           {
               //将每个条目添加到字典中。
               字典<字符串,对象> listDict = new Dictionary<字符串, 对象>();
               foreach(listType.Columns 中的 DataColumn dc)
               {
                   listDict.Add(dc.ColumnName, row[dc.ColumnName].ToString());
               }
               itemsList.Add(listDict);
           }
           结果[listType.TableName] = itemsList;

           返回结果;
       }
       return new Dictionary();
   }

}

享受!
马克·布里托

MVC / JSONP / DataSet Binding

I was able to get JSONP to work with MVC by modifying the code above. This sample directly binds datasets to html elements via JSONP.

Controller

>

public class HomeController : Controller
{
[HttpGet]
public ActionResult HeaderJSONP()
{
DsPromotion.HeaderDataTable tbl = new DsPromotion.HeaderDataTable();
DsPromotion.HeaderRow row = tbl.NewHeaderRow();
row.imgBanner_src = "/Content/Home/Image/MainBanner.gif";
tbl.Rows.Add(row);
return new JsonpResult { Data = tbl };
}
}

JSONP Result

> public class JsonpResult : System.Web.Mvc.JsonResult
>    {
>        public override void ExecuteResult(ControllerContext context)
>        {
>            this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
>            if (context == null)
>            {
>                throw new ArgumentNullException("context");
>            }
>
>            HttpResponseBase response = context.HttpContext.Response;
>            if (!String.IsNullOrEmpty(ContentType))
>            {
>                response.ContentType = ContentType;
>            }
>            else
>            {
>                response.ContentType = "application/json";
>            }
>            if (ContentEncoding != null)
>            {
>                response.ContentEncoding = ContentEncoding;
>            }
>            if (Data != null)
>            {
>                HttpRequestBase request = context.HttpContext.Request;
>                JavaScriptSerializer jsonserializer = new JavaScriptSerializer();
>                DataTableConverter serializer = new DataTableConverter();
>                response.Write(request.Params["jsoncallback"] + "(" + jsonserializer.Serialize(serializer.Serialize(Data, new JavaScriptSerializer())) + ")");
>            }
>        }
>    }

Javascript / JQuery JSON Request and Callback

>

function BindDataTable(dataTable) {
var tableName;
for (tableName in dataTable) {
if (tableName.indexOf('') > 0) {
tableName = tableName.split('
')[0];
}
}
var elementAndAttrib;
for (elementAndAttrib in dataTable[tableName][0]) {
var elementID = elementAndAttrib.split('')[0];
var attribName = elementAndAttrib.split('
')[1];
var attribValue = dataTable[tableName][0][elementAndAttrib];
$("#" + elementID).attr(attribName, attribValue);
}
}
function GetHomeHeaderCallBack(tblHeader) {
BindDataTable(tblHeader);
}
function GetHomeHeader() {
var call = "/Home/HeaderJSONP?jsoncallback=?&" + Math.round(new Date().getTime());
$.getJSON(call, { format: "json" }, GetHomeHeaderCallBack);
}
$(GetHomeHeader);

Partial View

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

XSD

...

Table Serializer

>

public class DataTableConverter : JavaScriptConverter
{
public override IEnumerable SupportedTypes
{
get { return new Type[] { typeof(DataTable) }; }
}

   public override object Deserialize(IDictionary<string, object> dictionary, Type type,
   JavaScriptSerializer serializer)
   {
       throw new NotImplementedException();
   }

   public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
   {
       DataTable listType = obj as DataTable;

       if (listType != null)
       {
           // Create the representation.
           Dictionary<string, object> result = new Dictionary<string, object>();
           ArrayList itemsList = new ArrayList();
           foreach (DataRow row in listType.Rows)
           {
               //Add each entry to the dictionary.
               Dictionary<string, object> listDict = new Dictionary<string, object>();
               foreach (DataColumn dc in listType.Columns)
               {
                   listDict.Add(dc.ColumnName, row[dc.ColumnName].ToString());
               }
               itemsList.Add(listDict);
           }
           result[listType.TableName] = itemsList;

           return result;
       }
       return new Dictionary<string, object>();
   }

}

Enjoy!
Mark Brito

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文