The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CORSModule.cs 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using Teknik.Configuration;
  6. using Teknik.Utilities;
  7. namespace Teknik.Modules
  8. {
  9. public class CORSModule : IHttpModule
  10. {
  11. public void Dispose()
  12. {
  13. }
  14. public void Init(HttpApplication context)
  15. {
  16. context.PreSendRequestHeaders += delegate(object sender, EventArgs args)
  17. {
  18. HttpContext requestContext = ((HttpApplication)sender).Context;
  19. Config config = Config.Load();
  20. // Allow this domain, or everything if local
  21. string origin = (requestContext.Request.IsLocal) ? "*" : requestContext.Request.Headers.Get("Origin");
  22. // Is the referrer set to the CDN and we are using a CDN?
  23. if (config.UseCdn && !string.IsNullOrEmpty(config.CdnHost))
  24. {
  25. try
  26. {
  27. string host = requestContext.Request.Headers.Get("Host");
  28. Uri uri = new Uri(config.CdnHost);
  29. if (host == uri.Host)
  30. origin = host;
  31. }
  32. catch { }
  33. }
  34. string domain = (string.IsNullOrEmpty(origin)) ? string.Empty : origin.GetDomain();
  35. if (string.IsNullOrEmpty(origin))
  36. {
  37. string sub = requestContext.Request.Url.Host.GetSubdomain();
  38. origin = (string.IsNullOrEmpty(sub)) ? config.Host : sub + "." + config.Host;
  39. }
  40. else
  41. {
  42. if (domain != config.Host)
  43. {
  44. string sub = origin.GetSubdomain();
  45. origin = (string.IsNullOrEmpty(sub)) ? config.Host : sub + "." + config.Host;
  46. }
  47. }
  48. requestContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  49. };
  50. }
  51. }
  52. }