json - ASP.net MVC 返回 JSONP

标签 json asp.net-mvc jsonp

我希望跨域返回一些 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
        }
    }
}

还有我所有 Controller 的父类(super class)的几个方法:

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

像魅力一样工作。

最佳答案

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

使用 jQuery 的客户端代码:

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

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

 public ContentResult JsonpCall(string callback)
 {
      return Content(String.Format("{0}({1});",
          callback, 
          new JavaScriptSerializer().Serialize(new { a = 1 })),    
          "application/javascript");
 }

关于json - ASP.net MVC 返回 JSONP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/758879/

相关文章:

javascript - Google map 更改单选按钮选择上 JSON 覆盖的填充颜色

java - 如何从 .json 文件中删除元素?

android - 如何在android的Horizo​​ntal Scrollview中动态加载json图片和文本?

c# - Foreach 不会将每个项目从 foreach 添加到 ViewModel

c# - MVC3 View 无法找到添加的引用类

javascript - JSONP 请求中可以提交的内容是否有限制?

arrays - PostgreSQL 索引 JSONB 数组

asp.net-mvc - ASP.NET MVC以编程方式获取 Controller 列表

jquery - JSONP 与 Rails

json - 覆盖 ExtJS 4 Store 中的默认参数名称