Skip to content

Instantly share code, notes, and snippets.

@Injac
Last active December 21, 2015 15:49
Show Gist options
  • Save Injac/6329543 to your computer and use it in GitHub Desktop.
Save Injac/6329543 to your computer and use it in GitHub Desktop.
A JSONP media-type formatter for ASP .NET WebApi (latest stable version). Copy the class and add this to your Global.asax.s var config = GlobalConfiguration.Configuration; config.Formatters.Add(new JsonpFormatter(null,null)); Original code from: https://gist.github.com/jonathanhunt/2967547
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Test
{
public class JsonpFormatter : MediaTypeFormatter
{
private readonly string _callbackQueryParameter;
private readonly JsonSerializerSettings _jsonSerializerSettings;
public JsonpFormatter(JsonSerializerSettings jsonSerializerSettings, string callbackQueryParameter)
{
_jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();
_callbackQueryParameter = callbackQueryParameter ?? "callback";
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
}
private string CallbackFunction { get; set; }
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var serializer = JsonSerializer.Create(_jsonSerializerSettings);
return Task.Factory.StartNew(() =>
{
using (var streamReader = new StreamReader(readStream, Encoding.UTF8))
{
using (var jsonTextReader = new JsonTextReader(streamReader))
{
return serializer.Deserialize(jsonTextReader, type);
}
}
});
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var serializer = JsonSerializer.Create(_jsonSerializerSettings);
var isJsonp = !string.IsNullOrEmpty(CallbackFunction);
return Task.Factory.StartNew(() =>
{
using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, Encoding.UTF8)) { CloseOutput = false })
{
if (isJsonp)
{
jsonTextWriter.WriteRaw(CallbackFunction + "(");
jsonTextWriter.Flush();
}
serializer.Serialize(jsonTextWriter, value);
jsonTextWriter.Flush();
if (isJsonp)
{
jsonTextWriter.WriteRaw(")");
jsonTextWriter.Flush();
}
}
});
}
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
var formatter = new JsonpFormatter(_jsonSerializerSettings, _callbackQueryParameter)
{
CallbackFunction = GetJsonCallbackFunction(request)
};
return formatter;
}
private string GetJsonCallbackFunction(HttpRequestMessage request)
{
if (request.Method != HttpMethod.Get) return null;
var query = request.RequestUri.ParseQueryString();
var queryVal = query[_callbackQueryParameter];
if (string.IsNullOrEmpty(queryVal)) return null;
return queryVal;
}
}
}
@ranaki
Copy link

ranaki commented Sep 19, 2013

I'm new to .Net WebAPI and am having the CORS problem so I am trying the JSONP formatter. It appears that I have successfully added this to my webapi project as described above. What is a simple way to verify that the JSONP formatter is functioning?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment