72

我希望跨域返回一些 JSON,并且我知道这样做的方法是通过 JSONP 而不是纯 JSON。
我正在使用 ASP.net MVC,所以我正在考虑扩展JsonResult类型,然后扩展 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
        }
    }
}

以及我所有控制器的超类的几种方法:

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
    };
}

奇迹般有效。

4

7 回答 7

17

这是一个简单的解决方案,如果您不想定义操作过滤器

使用 jQuery 的客户端代码:

  $.ajax("http://www.myserver.com/Home/JsonpCall", { dataType: "jsonp" }).done(function (result) {});

MVC 控制器动作。通过 JavaScript 代码执行查询字符串提供的回调函数返回内容结果。还为响应设置 JavaScript MIME 类型。

 public ContentResult JsonpCall(string callback)
 {
      return Content(String.Format("{0}({1});",
          callback, 
          new JavaScriptSerializer().Serialize(new { a = 1 })),    
          "application/javascript");
 }
于 2013-03-20T01:13:03.327 回答
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};
    }
}

这样您就不必担心创建所有不同的 Jsonp() 重载,只需将您的 JsonResult 转换为 Jsonp 即可。

于 2010-12-14T17:50:23.813 回答
10

Ranju 的博文(又名“我找到的这篇博文”)非常棒,阅读它可以让您进一步了解下面的解决方案,以便您的控制器可以在同一个控制器操作中优雅地处理同域 JSON 和跨域 JSONP 请求,而无需附加代码[在操作中]。

无论如何,对于“给我代码”类型,这里是,以防博客再次消失。

在您的控制器中(此代码段是新的/非博客代码):

[AllowCrossSiteJson]
public ActionResult JsonpTime(string callback)
{
    string msg = DateTime.UtcNow.ToString("o");
    return new JsonpResult
    {
        Data = (new
        {
            time = msg
        })
    };
}

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
        }
    }
}

注意:跟进@Ranju 和其他人对 OP 的评论,我认为值得将 Ranju 博客文章中的“最低限度”功能代码作为社区 wiki 发布。虽然可以肯定地说 Ranju 在他的博客上添加了上述代码和其他代码以供自由使用,但我不会在这里复制他的话。

于 2013-11-08T14:51:19.107 回答
2

对于ASP.NET Core,NOT ASP.NET MVC 这是针对答案中存在的解决方案的ASP.NET CORE
的 定制版本

public class JsonpResult : JsonResult
{
    public JsonpResult(object value) : base(value)
    {
    }

    public override async Task ExecuteResultAsync(ActionContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        HttpResponse response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
            response.ContentType = ContentType;
        else
            response.ContentType = "application/javascript";

        if (Value != null)
        {
            HttpRequest request = context.HttpContext.Request;
            string serializedJson = JsonConvert.SerializeObject(Value);
            string result = $"{request.Query["callback"]}({serializedJson})";
            await response.WriteAsync(result);
        }
    }
}

于 2020-07-26T20:10:41.327 回答
0

stimms 和 ranju v 的参考文章都非常有用,并且清楚地说明了情况。

然而,我对在网上找到的 MVC 代码的上下文中使用扩展、子类化感到摸不着头脑。

有两个关键点让我印象深刻:

  1. 我从 ActionResult 派生的代码,但在 ExecuteResult 中有一些代码可以返回 XML 或 JSON。
  2. 然后,我创建了一个基于泛型的 ActionResult,以确保使用相同的 ExecuteResults,而与我返回的数据类型无关。

因此,将两者结合起来——我不需要进一步的扩展或子类化来添加返回 JSONP 的机制,只需更改我现有的 ExecuteResults。

让我感到困惑的是,我真的在寻找一种方法来派生或扩展 JsonResult,而无需重新编码 ExecuteResult。由于 JSONP 实际上是一个带有前缀和后缀的 JSON 字符串,因此它似乎是一种浪费。然而,下面的 ExecuteResult 使用 respone.write - 所以最安全的更改方法是重新编码 ExecuteResults,因为各种帖子很容易提供!

如果有用的话,我可以发布一些代码,但是这个线程中已经有很多代码了。

于 2011-07-16T08:33:58.720 回答
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Template.Web.Helpers
{
    public class JsonpResult : JsonResult
    {
        public JsonpResult(string callbackName)
        {
            CallbackName = callbackName;
        }

        public JsonpResult()
            : this("jsoncallback")
        {
        }

        public string CallbackName { get; set; }

        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[CallbackName] as string) ?? request[CallbackName]) ?? CallbackName;

            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(")");
            }
        }
    }

    public static class ControllerExtensions
    {
        public static JsonpResult Jsonp(this Controller controller, object data, string callbackName = "callback")
        {
            return new JsonpResult(callbackName)
            {
                Data = data,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        public static T DeserializeObject<T>(this Controller controller, string key) where T : class
        {
            var value = controller.HttpContext.Request.QueryString.Get(key);
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            return javaScriptSerializer.Deserialize<T>(value);
        }
    }
}

//Example of using the Jsonp function::
//  1-
public JsonResult Read()
{
    IEnumerable<User> result = context.All();        

    return this.Jsonp(result);
}

//2-
public JsonResult Update()
{
    var models = this.DeserializeObject<IEnumerable<User>>("models");
    if (models != null)
    {
        Update(models); //Update properties & save change in database
    }
    return this.Jsonp(models);
}
于 2015-08-27T14:15:12.423 回答
-2

上面的解决方案是一种很好的工作方式,但它应该使用一种新的结果类型进行扩展,而不是使用返回 JsonResult 的方法,您应该编写返回您自己的结果类型的方法

public JsonPResult testMethod() {
    // use the other guys code to write a method that returns something
}

public class JsonPResult : JsonResult
{
    public FileUploadJsonResult(JsonResult data) {
        this.Data = data;
    }      

    public override void ExecuteResult(ControllerContext context)
    {
        this.ContentType = "text/html";
        context.HttpContext.Response.Write("<textarea>");
        base.ExecuteResult(context);
        context.HttpContext.Response.Write("</textarea>");
    }
}
于 2011-02-09T19:38:52.577 回答