Skip to content

Instantly share code, notes, and snippets.

@shengoo
Last active August 29, 2015 14:09
Show Gist options
  • Save shengoo/0f365e6dda2f910dccc7 to your computer and use it in GitHub Desktop.
Save shengoo/0f365e6dda2f910dccc7 to your computer and use it in GitHub Desktop.
add jsonp support for .net web api
public class JsonpAttribute : 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment