Repository navigation
Expand file tree
/
Copy pathEnableCorsAttribute.cs
More file actions
54 lines (45 loc) · 2.34 KB
/
Copy pathEnableCorsAttribute.cs
File metadata and controls
54 lines (45 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Threading.Tasks;
using ServiceStack.Web;
namespace ServiceStack
{
/// <summary>
/// Attribute marks that specific response class has support for Cross-origin resource sharing (CORS, see http://www.w3.org/TR/access-control/). CORS allows to access resources from different domain which usually forbidden by origin policy.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class EnableCorsAttribute : AttributeBase, IHasRequestFilterAsync
{
public int Priority { get; set; } = 0;
public bool AutoHandleOptionRequests { get; set; }
private readonly string allowedOrigins;
private readonly string allowedMethods;
private readonly string allowedHeaders;
private readonly bool allowCredentials;
/// <summary>
/// Represents a default constructor with Allow Origin equals to "*", Allowed GET, POST, PUT, DELETE, OPTIONS request and allowed "Content-Type" header.
/// </summary>
public EnableCorsAttribute(string allowedOrigins = "*", string allowedMethods = CorsFeature.DefaultMethods, string allowedHeaders = CorsFeature.DefaultHeaders, bool allowCredentials = false)
{
this.allowedOrigins = allowedOrigins;
this.allowedMethods = allowedMethods;
this.allowedHeaders = allowedHeaders;
this.allowCredentials = allowCredentials;
this.AutoHandleOptionRequests = true;
}
public Task RequestFilterAsync(IRequest req, IResponse res, object requestDto)
{
if (!string.IsNullOrEmpty(allowedOrigins))
res.AddHeader(HttpHeaders.AllowOrigin, allowedOrigins);
if (!string.IsNullOrEmpty(allowedMethods))
res.AddHeader(HttpHeaders.AllowMethods, allowedMethods);
if (!string.IsNullOrEmpty(allowedHeaders))
res.AddHeader(HttpHeaders.AllowHeaders, allowedHeaders);
if (allowCredentials)
res.AddHeader(HttpHeaders.AllowCredentials, "true");
if (AutoHandleOptionRequests && req.Verb == HttpMethods.Options)
res.EndRequest();
return TypeConstants.EmptyTask;
}
public IRequestFilterBase Copy() => (IRequestFilterBase)MemberwiseClone();
}
}