-
-
Save brandanmajeske/1a91ef869b98b256bba5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using global::ServiceStack; | |
using global::ServiceStack.Common.Web; | |
using global::ServiceStack.WebHost.Endpoints; | |
public class CorsFeature : IPlugin | |
{ | |
public const string DefaultMethods = "GET, POST, PUT, DELETE, OPTIONS"; | |
public const string DefaultHeaders = "Content-Type"; | |
private static bool isInstalled = false; | |
private readonly string _allowedMethods; | |
private readonly string _allowedHeaders; | |
private readonly bool _allowCredentials; | |
private readonly bool _autoHandleOptionsRequest; | |
private readonly ICollection<string> allowedOrigins; | |
/// <summary> | |
/// Represents a default constructor with Allow Origin equals to "*", Allowed GET, POST, PUT, DELETE, OPTIONS request and allowed "Content-Type" header. | |
/// </summary> | |
public CorsFeature(ICollection<string> allowedOrigins, string allowedMethods = DefaultMethods, string allowedHeaders = DefaultHeaders, bool allowCredentials = true, bool autoHandleOptionsRequest = true) | |
{ | |
this._allowedMethods = allowedMethods; | |
this._allowedHeaders = allowedHeaders; | |
this._allowCredentials = allowCredentials; | |
this.allowedOrigins = allowedOrigins; | |
this._autoHandleOptionsRequest = autoHandleOptionsRequest; | |
} | |
public void Register(IAppHost appHost) | |
{ | |
if (isInstalled) return; | |
isInstalled = true; | |
if (!string.IsNullOrEmpty(this._allowedMethods)) | |
appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowMethods, this._allowedMethods); | |
if (!string.IsNullOrEmpty(this._allowedHeaders)) | |
appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowHeaders, this._allowedHeaders); | |
if (this._allowCredentials) | |
appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowCredentials, "true"); | |
if (this.allowedOrigins != null || this._autoHandleOptionsRequest) | |
{ | |
appHost.RequestFilters.Add((httpReq, httpRes, requestDto) => | |
{ | |
if (this.allowedOrigins != null) | |
{ | |
var origin = httpReq.Headers.Get("Origin"); | |
if (origin != null && (this.allowedOrigins.Contains("*") || this.allowedOrigins.Contains(origin))) | |
{ | |
httpRes.AddHeader(HttpHeaders.AllowOrigin, origin); | |
} | |
} | |
if (this._autoHandleOptionsRequest && httpReq.HttpMethod == HttpMethods.Options) | |
httpRes.EndRequest(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment