sti*_*mms 72 asp.net-mvc json jsonp
我希望跨域返回一些JSON,我知道这样做的方法是通过JSONP而不是纯JSON.我正在使用ASP.net MVC所以我正在考虑只是扩展JSONResult类型然后extendig Controller,以便它还实现了一个Jsonp方法.这是最好的解决方法,还是内置的ActionResult可能会更好?
编辑:我继续前进并做到了.仅供参考,我添加了一个新结果:
public class JsonpResult : System.Web.Mvc.JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/javascript";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
HttpRequestBase request = context.HttpContext.Request;
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")");
#pragma warning restore 0618
}
}
}
Run Code Online (Sandbox Code Playgroud)
以及我所有控制器的超类的几种方法:
protected internal JsonpResult Jsonp(object data)
{
return Jsonp(data, null /* contentType */);
}
protected internal JsonpResult Jsonp(object data, string contentType)
{
return Jsonp(data, contentType, null);
}
protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding)
{
return new JsonpResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}
Run Code Online (Sandbox Code Playgroud)
奇迹般有效.
Mak*_*nko 16
如果您不想定义动作过滤器,这是一个简单的解决方案
使用jQuery的客户端代码:
$.ajax("http://www.myserver.com/Home/JsonpCall", { dataType: "jsonp" }).done(function (result) {});
Run Code Online (Sandbox Code Playgroud)
MVC控制器动作.返回内容结果,JavaScript代码执行随查询字符串提供的回调函数.还为响应设置JavaScript MIME类型.
public ContentResult JsonpCall(string callback)
{
return Content(String.Format("{0}({1});",
callback,
new JavaScriptSerializer().Serialize(new { a = 1 })),
"application/javascript");
}
Run Code Online (Sandbox Code Playgroud)
小智 13
我没有使用Jsonp()方法对我的控制器进行子类化,而是使用了扩展方法路径,因为它让我感觉更干净.关于JsonpResult的好处是你可以像测试JsonResult一样测试它.
我做了:
public static class JsonResultExtensions
{
public static JsonpResult ToJsonp(this JsonResult json)
{
return new JsonpResult { ContentEncoding = json.ContentEncoding, ContentType = json.ContentType, Data = json.Data, JsonRequestBehavior = json.JsonRequestBehavior};
}
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必担心创建所有不同的Jsonp()重载,只需将JsonResult转换为Jsonp.
ruf*_*fin 10
Ranju的博客文章(又名"我发现的这篇博文")非常好,阅读它将允许您进一步解决下面的解决方案,以便您的控制器可以在同一控制器操作中优雅地处理同域JSON和跨域JSONP请求附加代码[在行动中].
无论如何,对于"给我代码"类型,这里是,如果博客再次消失.
在您的控制器中(此代码段是新的/非博客代码):
[AllowCrossSiteJson]
public ActionResult JsonpTime(string callback)
{
string msg = DateTime.UtcNow.ToString("o");
return new JsonpResult
{
Data = (new
{
time = msg
})
};
}
Run Code Online (Sandbox Code Playgroud)
JsonpResult在这篇优秀的博文中发现 :
/// <summary>
/// Renders result as JSON and also wraps the JSON in a call
/// to the callback function specified in "JsonpResult.Callback".
/// http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
/// </summary>
public class JsonpResult : JsonResult
{
/// <summary>
/// Gets or sets the javascript callback function that is
/// to be invoked in the resulting script output.
/// </summary>
/// <value>The callback function name.</value>
public string Callback { get; set; }
/// <summary>
/// Enables processing of the result of an action method by a
/// custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>.
/// </summary>
/// <param name="context">The context within which the
/// result is executed.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = "application/javascript";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Callback == null || Callback.Length == 0)
Callback = context.HttpContext.Request.QueryString["callback"];
if (Data != null)
{
// The JavaScriptSerializer type was marked as obsolete
// prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
JavaScriptSerializer serializer = new JavaScriptSerializer();
string ser = serializer.Serialize(Data);
response.Write(Callback + "(" + ser + ");");
#pragma warning restore 0618
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:跟随@Ranju和其他人对OP的评论,我认为值得将Ranju的博客文章中的"最低限度"功能代码作为社区维基发布.虽然可以说Ranju在他的博客上添加了上述和其他代码以便自由使用,但我不打算在这里复制他的话.
| 归档时间: |
|
| 查看次数: |
36742 次 |
| 最近记录: |