title: ASP.NET MVC 5 - Dynamically set CORS
body: <p>In my MVC5 application, I've a controller that can be called from client applications (AngularJs in my case) and returns JSON.
  For this particular Controller/Action, I want to set the Access-Control-Allow-Origin dynamically, depending of the "client_id" params in QueryString.</p>
  
  <p>My problem is that I can't find a way to handle the Http Options request from the browser...</p>
  
  <p>I've try many solutions:</p>
  
  <p><strong>1- [HttpOptions] Attribute on top of the Action Controller</strong>:
  The code is never executed called</p>
  
  <pre><code>[HttpOptions]
  public virtual ActionResult Refresh(string client_id)
  {
       // This code is never executed
       // Should be setting CORS depending on the client_id
  }
  
  [HttpPost]
  public virtual ActionResult Refresh(string client_id, FormCollection form)
  {
       // This is executed after the browser Http Options Request
  }
  </code></pre>
  
  <p><strong>2- Create my own ActionFilter, and put the CORS Headers from this filter</strong>: Never handle the Http Options Request.</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
  public class ApplicationCrossOriginAttribute : ActionFilterAttribute
  {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
          // This code is never executed on Http Options Request
          // Set custom CORS header here on Http Options Request
          base.OnActionExecuting(filterContext);
      }
  }
  </code></pre>
  
  <p><strong>3- Use Global.asax Application_BeginRequest Event</strong>: Once again, the code is never reach with an Http Options Request...</p>
  
  <p>I've so tried to simply configure CORS from the Web.config file, but I don't want to hardcode the Origins (and I can't since it's all domains are dynamic...)
  But, yeah, everything works perfectly with this configuration:</p>
  
  <pre><code>&lt;system.webServer&gt;
    &lt;httpProtocol&gt;
      &lt;customHeaders&gt;
        &lt;clear/&gt;
        &lt;add name="Access-Control-Allow-Origin" value="*" /&gt;&lt;!--Not dynamic here--&gt;
        &lt;add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" /&gt;
        &lt;add name="Access-Control-Allow-Headers" value="Accept,Authorization" /&gt;
      &lt;/customHeaders&gt;
    &lt;/httpProtocol&gt;
  &lt;/system.webServer&gt;
  </code></pre>
  
  <p>I'm stuck here, as i don't know how to fill my needs...</p>