0

I'm using ASP.NET Web API v2.0 to build an web api.

I need to make some of the controllers/actions available in CORS/JSONP, so I chose to use WebApiContrib.Formatting.Jsonp.

Because I'm not use Web API v2.1 yet, I can only use WebApiContrib v0.9.7.0.

If I add the JSONP formatter in Global.ascx.cs, it'll open all my controllers and actions for CORS/JSONP, so I wrote the Action Filter below to add and remove the formatter at specific times.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var config = System.Web.Http.GlobalConfiguration.Configuration;
        config.Formatters.Insert(0, new WebApiContrib.Formatting.Jsonp.JsonpMediaTypeFormatter(config.Formatters.JsonFormatter));
    }

    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {
        var config = System.Web.Http.GlobalConfiguration.Configuration;
        config.Formatters.RemoveAt(0);
    }
}

Now, my question is that will that code be thread safe if multiple requests are coming in?

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
  • There is no data you are sharing in these methods so there is no thread safety issue. – T McKeown Jul 28 '14 at 20:46
  • @TMcKeown, but the code is adding and removing the formatter in global config. If request A takes too long to run, and request B came in, won't that also allow request B to use the formatter even if it's not attributed? – Ray Cheng Jul 28 '14 at 20:49
  • ok, oops... YES... you are correct... you should lock/synch that code. sorry.. i understand it now – T McKeown Jul 28 '14 at 20:51
  • add a `private static object _syncRoot = new object();` and use that. – T McKeown Jul 28 '14 at 20:52

0 Answers0