C# - Easily enabling a webapi or mvc endpoint to deliver JSONP

You can use the following ActionFilterAttribute (annotation) to enable an endpoint to return JSONP. The below example is for webapi but can also be applied to mvc with a few tweaks.

using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;

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());


Even though JSONP is rarely used these days thanks to modern browsers, you may need it for older browsers. If you are only supporting modern browsers then please have a look at CORS.