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:31

We can solve CORS(Cross-origin resource sharing)issue using two ways,

1)Using Jsonp 2)Enabling the Cors

1)Using Jsonp- to use the Jsonp we need to install WebApiContrib.Formatting.Jsonp nuget package and need to add JsonpFormmater in WebApiConfig.cs refer screenshots,enter image description here

Jquery code enter image description here

2)Enabling the Cors -

to enable the cors we need to add Microsoft.AspNet.WebApi.Cors nuget package and need to enable cors in WebApiConfig.cs refer screenshot

enter image description here

For more reference, you can refer my sample repo on GitHub using the following link. https://github.com/mahesh353/Ninject.WebAPi/tree/develop

查看更多
墨雨无痕
3楼-- · 2019-01-01 10:35

After asking this question, I finally found what I needed, so I am answering it.

I ran across this JsonpMediaTypeFormatter. Add it into the Application_Start of your global.asax by doing this:

var config = GlobalConfiguration.Configuration;
config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

and you are good to go with an JQuery AJAX call that looks like this:

$.ajax({
    url: 'http://myurl.com',
    type: 'GET',
    dataType: 'jsonp',
    success: function (data) {
        alert(data.MyProperty);
    }
})

It seems to work very well.

查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 10:37

Updated

public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
    {
        private string callbackQueryParameter;

        public JsonpMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(DefaultMediaType);
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

            MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType));
        }

        public string CallbackQueryParameter
        {
            get { return callbackQueryParameter ?? "callback"; }
            set { callbackQueryParameter = value; }
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            string callback;

            if (IsJsonpRequest(out callback))
            {
                return Task.Factory.StartNew(() =>
                {
                    var writer = new StreamWriter(writeStream);
                    writer.Write(callback + "(");
                    writer.Flush();

                    base.WriteToStreamAsync(type, value, writeStream, content, transportContext).Wait();

                    writer.Write(")");
                    writer.Flush();
                });
            }
            else
            {
                return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
            }
        }

        private bool IsJsonpRequest(out string callback)
        {
            callback = null;

            if (HttpContext.Current.Request.HttpMethod != "GET")
                return false;

            callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];

            return !string.IsNullOrEmpty(callback);
        }
    }
查看更多
登录 后发表回答