C# - Enabling a Webapi or MVC endpoint to deliver JSONP with an example

You can use the following ActionFilterAttribute (annotation) to enable an endpoint to return JSONP. The below example is for webapi and .Net Framework but it can 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, which I have a post on here.

I hope the above helped you, please let me know if it did down in the comments below :)