JSONP with ASP.NET Web API

2019-01-01 10:00发布

I am working on creating a new set of services in ASP.MVC MVC 4 using the Web API. So far, it's great. I have created the service and gotten it to work, and now I am trying to consume it using JQuery. I can get back the JSON string using Fiddler, and it seems to be ok, but because the service exists on a separate site, trying to call it with JQuery errors with the "Not Allowed". So, this is clearly a case where I need to use JSONP.

I know that the Web API is new, but I'm hoping someone out there can help me.

How do I make a call to a Web API method using JSONP?

15条回答
牵手、夕阳
2楼-- · 2019-01-01 10:22

You can use an ActionFilterAttribute like this:

public class JsonCallbackAttribute : ActionFilterAttribute
{
    private const string CallbackQueryParameter = "callback";

    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var callback = string.Empty;

        if (IsJsonp(out callback))
        {
            var jsonBuilder = new StringBuilder(callback);

            jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);

            context.Response.Content = new StringContent(jsonBuilder.ToString());
        }

        base.OnActionExecuted(context);
    }

    private bool IsJsonp(out string callback)
    {
        callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];

        return !string.IsNullOrEmpty(callback);
    }
}

Then put it on your action:

[JsonCallback]
public IEnumerable<User> User()
{
    return _user;
}
查看更多
初与友歌
3楼-- · 2019-01-01 10:22

Check this one out. See if it helps.

JSONP with Web API

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 10:22

If the context is Web Api, thanking and referring to 010227leo's answer, you must consider WebContext.Current value which is going to be null.

So I updated his code to this:

public class JsonCallbackAttribute
    : ActionFilterAttribute
{
    private const string CallbackQueryParameter = "callback";

    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        var callback = context.Request.GetQueryNameValuePairs().Where(item => item.Key == CallbackQueryParameter).Select(item => item.Value).SingleOrDefault();

        if (!string.IsNullOrEmpty(callback))
        {
            var jsonBuilder = new StringBuilder(callback);

            jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);

            context.Response.Content = new StringContent(jsonBuilder.ToString());
        }

        base.OnActionExecuted(context);
    }
}
查看更多
长期被迫恋爱
5楼-- · 2019-01-01 10:25

JSONP only works with Http GET request. There is a CORS support in asp.net web api which works well with all http verbs.

This article may be helpful to you.

查看更多
ら面具成の殇う
6楼-- · 2019-01-01 10:28

Unfortunately, I don't have enough reputation to comment, so I'll post an answer. @Justin raised the issue of running the WebApiContrib.Formatting.Jsonp formatter alongside the standard JsonFormatter. That issue is resolved in the latest release (actually released some time ago). Also, it should work with the latest Web API release.

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 10:31

Instead of hosting your own JSONP formatter version you can install WebApiContrib.Formatting.Jsonp NuGet package with already implemented one (choose the version that works for your .NET Framework).

Add this formatter into Application_Start:

GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
查看更多
登录 后发表回答