Skip to content

Instantly share code, notes, and snippets.

@wayne-o
Created March 19, 2012 08:42
Show Gist options
  • Save wayne-o/2103389 to your computer and use it in GitHub Desktop.
Save wayne-o/2103389 to your computer and use it in GitHub Desktop.
CORS
private Stream ReturnAsStream<T>(T toSerialize)
{
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var json = JsonConvert.SerializeObject(toSerialize, Formatting, settings);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
}
private static bool AllowCors()
{
//for all cors requests
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Origin", "*");
//identify preflight request and add extra headers
if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
{
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE");
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Headers",
"Content-Type, Accept, Authorization, x-requested-with");
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment