Last active
August 29, 2015 14:09
-
-
Save shengoo/0f365e6dda2f910dccc7 to your computer and use it in GitHub Desktop.
add jsonp support for .net web api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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