WcsServerHost.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Web.Http;
  3. using System.Web.Http.Cors;
  4. using System.Web.Http.SelfHost;
  5. namespace WCS.API
  6. {
  7. public class WcsServerHost
  8. {
  9. private static WcsServerHost instance = null;
  10. private static HttpSelfHostServer httpSelfHostServer = null;
  11. private static readonly object obj_Locker = new object();
  12. private WcsServerHost()
  13. {
  14. }
  15. public static WcsServerHost Instance
  16. {
  17. get
  18. {
  19. if (instance == null)
  20. {
  21. lock (obj_Locker)
  22. {
  23. if (instance == null)
  24. {
  25. instance = new WcsServerHost();
  26. }
  27. }
  28. }
  29. return instance;
  30. }
  31. }
  32. public string GetStr()
  33. {
  34. return "=================================";
  35. }
  36. public bool CloseServer()
  37. {
  38. try
  39. {
  40. if (httpSelfHostServer != null)
  41. {
  42. httpSelfHostServer.CloseAsync();
  43. }
  44. return true;
  45. }
  46. catch (Exception ex)
  47. {
  48. Console.WriteLine(ex.ToString());
  49. return false;
  50. }
  51. }
  52. public bool StartServer(string uri)
  53. {
  54. try
  55. {
  56. // string address = "http://localhost:3350";192.168.2.54:3350/api/AgvMes/ReleaseAGV
  57. HttpSelfHostConfiguration httpSelfHostConfiguration = new HttpSelfHostConfiguration(uri);
  58. httpSelfHostConfiguration.Formatters.Remove(httpSelfHostConfiguration.Formatters.XmlFormatter);
  59. httpSelfHostConfiguration.Formatters.Add(httpSelfHostConfiguration.Formatters.JsonFormatter);
  60. httpSelfHostConfiguration.Routes.MapHttpRoute //Ìí¼Ó·ÓÉ
  61. (name: "wcsapi",
  62. routeTemplate: "api/{controller}/{action}/{id}",
  63. defaults: new { id = RouteParameter.Optional });
  64. EnableCorsAttribute enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
  65. httpSelfHostConfiguration.EnableCors(enableCorsAttribute);
  66. httpSelfHostServer = new HttpSelfHostServer(httpSelfHostConfiguration);
  67. httpSelfHostServer.OpenAsync().Wait();
  68. return true;
  69. }
  70. catch (Exception ex)
  71. {
  72. Console.WriteLine(ex.ToString());
  73. return false;
  74. }
  75. }
  76. }
  77. }