Tôi đang tìm cách trả về một số JSON trên các tên miền và tôi hiểu rằng cách để làm điều này là thông qua JSONP chứ không phải là JSON thuần túy. Tôi đang sử dụng ASP.net MVC vì vậy tôi đã suy nghĩ về chỉ cần mở rộng các loại JSONResult và sau đó extendig Controller để nó cũng thực hiện một phương pháp Jsonp. Đây có phải là cách tốt nhất để đi về nó hoặc có tích hợp trong ActionResult mà có thể là tốt hơn?ASP.net MVC trả lại JSONP
Chỉnh sửa: Tôi đã tiếp tục và thực hiện điều đó. Chỉ vì tài liệu tham khảo tôi đã thêm một kết quả mới:
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
}
}
}
và cũng là một vài phương pháp để một lớp cha của tất cả các bộ điều khiển của tôi:
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
};
}
trình như một say mê.
Cảm ơn! Chỉ cần thực hiện điều này trong dự án của chúng tôi! :) –
Rất tuyệt! Nhưng JSONP phải được phân phối dưới dạng http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp –
xem thêm http://support.github.com/discussions/api/18 -content-type-should-applicationjavascript-for-jsonp-request http://stackapps.com/questions/1668/wrong-content-type-in-jsonp-calls –