.NET 处理jsonp请求,后台代码

首先我们需要定义一个JsonpResult. 代码像这样, 直接继承自JsonResult, override了ExecuteResult方法

public class JsonpResult : JsonResult
{
    private static readonly string JsonpCallbackName = "callback";
    private static readonly string CallbackApplicationType = "application/json";

    /// <summary>
    /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
    /// </summary>
    /// <param name="context">The context within which the result is executed.</param>
    /// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
              String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
        {
            throw new InvalidOperationException();
        }
        var response = context.HttpContext.Response;
        if (!String.IsNullOrEmpty(ContentType))
            response.ContentType = ContentType;
        else
            response.ContentType = CallbackApplicationType;
        if (ContentEncoding != null)
            response.ContentEncoding = this.ContentEncoding;
        if (Data != null)
        {
            String buffer;
            var request = context.HttpContext.Request;
            var serializer = new JavaScriptSerializer();
            if (request[JsonpCallbackName] != null)
                buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
            else
                buffer = serializer.Serialize(Data);
            response.Write(buffer);
        }
    }
}
接着简单定义一个扩展方法:
public static class ContollerExtensions
{
    /// <summary>
    /// Extension methods for the controller to allow jsonp.
    /// </summary>
    /// <param name="controller">The controller.</param>
    /// <param name="data">The data.</param>
    /// <returns></returns>
    public static JsonpResult Jsonp(this Controller controller, object data)
    {
        JsonpResult result = new JsonpResult()
        {
            Data = data,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
       
        return result;
    }
}

在Controller里使用它:

public JsonpResult GetInformation(string key)
{
    string resp = "HELLO WORD!"

    return this.Jsonp(resp);
}
现在让我们在另一个站点里使用它:
$.ajax({
    url: 'http://localhost:50211/Api/GetInformation',
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "localJsonpCallback"
});


function localJsonpCallback(json) {
    alert(json);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuanlongWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值