ASP.NET MVC 3 JSONP:这是否适用于 JsonValueProviderFactory? [英] ASP.NET MVC 3 JSONP: Does this work with JsonValueProviderFactory?
问题描述
Phil Haack 有一个出色的 博文 关于如何使用 JSON、数据绑定和数据验证.
Phil Haack has an excellent blog post on how to use JSON, data binding, and data validation.
输入浏览器的同源策略安全限制".和 JSONP,您可以在其中使用 $.getJSON() 来检索内容.
Enter the browser's "same origin policy security restriction." and JSONP where you use $.getJSON() to retrieve the content.
是否有内置的 MVC 3 方法来执行此操作,或者我是否需要遵循 posts 的建议像这样?可以发内容吗?我问是因为我的同事实现了一个 JsonPfilterAttribute 来完成这项工作.如果 MVC 3 中已经存在某些东西,显然最好避免这种情况.
Is there a built in MVC 3 way to do this, or do I need to follow the advice of posts like this? Can you post content? I ask because my colleague implemented a JsonPfilterAttribute among other things to make this work. It's obviously preferred to avoid that if something already exists in MVC 3.
总结:除了访问 POST
变量外,一切正常,即,我如何访问上下文中的 POST
变量?(在最后一段代码中注释标记)
Summary: everything works with the exception of accessing a POST
variable, i.e., how do I access the POST
variable in the context? (comment marking it in the last section of code)
我选择使用这种格式来调用服务器:
I elected to use this format to call the server:
$.ajax({
type: "GET",
url: "GetMyDataJSONP",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonpCallback: "randomFunctionName"
});
产生此响应的原因:
randomFunctionName([{"firstField":"111","secondField":"222"}]);
如果我使用 GET
,所有这些都非常有效.但是,我仍然无法让它作为 POST
工作.这是 Nathan Bridgewater 发布的原始代码 here一>.这一行没有找到 POST 数据:
And all this works very well if I use a GET
. However, I still cannot get this to work as a POST
. Here's the original code posted by Nathan Bridgewater here. This line doesn't find the POST data:
context.HttpContext.Request["callback"];
要么我应该以某种方式访问 Form
,要么 MVC 数据验证器正在剥离 POST 变量.
Either I should be accessing Form
in some way, or the MVC data validators are stripping out the POST variables.
应该如何编写 context.HttpContext.Request["callback"];
来访问 POST
变量,或者 MVC 出于某种原因剥离了这些值?
How should context.HttpContext.Request["callback"];
be written to access the POST
variable or is MVC stripping out these values for some reason?
namespace System.Web.Mvc
{ public class JsonpResult : ActionResult
{ public JsonpResult() {}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public string JsonCallback { get; set; }
public override void ExecuteResult(ControllerContext context)
{ if (context == null)
throw new ArgumentNullException("context");
this.JsonCallback = context.HttpContext.Request["jsoncallback"];
// This is the line I need to alter to find the form variable:
if (string.IsNullOrEmpty(this.JsonCallback))
this.JsonCallback = context.HttpContext.Request["callback"];
if (string.IsNullOrEmpty(this.JsonCallback))
throw new ArgumentNullException(
"JsonCallback required for JSONP response.");
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = "application/json; charset=utf-8";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{ JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(string.Format("{0}({1});", this.JsonCallback,
serializer.Serialize(Data)));
} } }
//extension methods for the controller to allow jsonp.
public static class ContollerExtensions
{
public static JsonpResult Jsonp(this Controller controller,
object data)
{
JsonpResult result = new JsonpResult();
result.Data = data;
result.ExecuteResult(controller.ControllerContext);
return result;
}
}
}
推荐答案
就接收 JSON 字符串并将其绑定到模型而言,JsonValueProviderFactory
在 ASP 中开箱即用地完成这项工作.NET MVC 3. 但是没有内置的用于输出 JSONP 的东西.你可以编写一个自定义的 JsonpResult
:
As far as receiving a JSON string and binding it to a model is concerned the JsonValueProviderFactory
does this job out of the box in ASP.NET MVC 3. But there is nothing built-in for outputting JSONP. You could write a custom JsonpResult
:
public class JsonpResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var request = context.HttpContext.Request;
var response = context.HttpContext.Response;
string jsoncallback = (context.RouteData.Values["jsoncallback"] as string) ?? request["jsoncallback"];
if (!string.IsNullOrEmpty(jsoncallback))
{
if (string.IsNullOrEmpty(base.ContentType))
{
base.ContentType = "application/x-javascript";
}
response.Write(string.Format("{0}(", jsoncallback));
}
base.ExecuteResult(context);
if (!string.IsNullOrEmpty(jsoncallback))
{
response.Write(")");
}
}
}
然后在您的控制器操作中:
And then in your controller action:
public ActionResult Foo()
{
return new JsonpResult
{
Data = new { Prop1 = "value1", Prop2 = "value2" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
可以从另一个域使用 $.getJSON()
:
which could be consumed from another domain with $.getJSON()
:
$.getJSON('http://domain.com/home/foo?jsoncallback=?', function(data) {
alert(data.Prop1);
});
这篇关于ASP.NET MVC 3 JSONP:这是否适用于 JsonValueProviderFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!