HttpService.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using Blazored.LocalStorage;
  2. using Microsoft.AspNetCore.Components;
  3. using Microsoft.AspNetCore.Components.Authorization;
  4. using Microsoft.Extensions.Configuration;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Http.Headers;
  11. using System.Net.Http.Json;
  12. using System.Text;
  13. using System.Text.Json;
  14. using System.Threading.Tasks;
  15. using wispro.sp.share.webViewObject;
  16. using wispro.sp.web.Auth;
  17. using wispro.sp.web.Utils;
  18. namespace wispro.sp.web.Services
  19. {
  20. public interface IHttpService
  21. {
  22. Task<T> Get<T>(string uri);
  23. Task<T> Post<T>(string uri, object value);
  24. Task<byte[]> Post(string uri, object value);
  25. }
  26. public class HttpService:IHttpService
  27. {
  28. private HttpClient _httpClient;
  29. private NavigationManager _navigationManager;
  30. private ILocalStorageService _localStorageService;
  31. private IConfiguration _configuration;
  32. //private IAuthService _authService;
  33. private AuthenticationStateProvider authenticationStateProvider;
  34. public HttpService(
  35. HttpClient httpClient,
  36. NavigationManager navigationManager,
  37. ILocalStorageService localStorageService,
  38. IConfiguration configuration,
  39. AuthenticationStateProvider authService
  40. )
  41. {
  42. _httpClient = httpClient;
  43. _httpClient.Timeout = TimeSpan.FromSeconds(1000);
  44. _navigationManager = navigationManager;
  45. _localStorageService = localStorageService;
  46. _configuration = configuration;
  47. authenticationStateProvider = authService;
  48. }
  49. public async Task<T> Get<T>(string uri)
  50. {
  51. var request = new HttpRequestMessage(HttpMethod.Get, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  52. return await sendRequest<T>(request);
  53. }
  54. public async Task<T> Post<T>(string uri, object value)
  55. {
  56. var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  57. request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
  58. return await sendRequest<T>(request);
  59. }
  60. public async Task<byte[]> Post(string uri, object value)
  61. {
  62. var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  63. //request.Headers.Add("Content-Type", "application/json");
  64. request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
  65. var data =await snedRequestNotReturn(request);
  66. return data;
  67. }
  68. private async Task<byte[]> snedRequestNotReturn(HttpRequestMessage request)
  69. {
  70. // add jwt auth header if user is logged in and request is to the api url
  71. try
  72. {
  73. var user = await _localStorageService.GetItemAsync<userToken>("authToken");
  74. var isApiUrl = !request.RequestUri.IsAbsoluteUri;
  75. if (user != null) // && isApiUrl)
  76. {
  77. //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
  78. //將token取出轉為claim
  79. var claims = JwtParser.ParseClaimsFromJwt(user.Token);
  80. //在每次request的header中帶入bearer token
  81. _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
  82. }
  83. }
  84. catch (Exception ex)
  85. {
  86. //Console.WriteLine(ex.ToString());
  87. }
  88. using HttpResponseMessage response = await _httpClient.SendAsync(request);
  89. // auto logout on 401 response
  90. if (response.StatusCode == HttpStatusCode.Unauthorized)
  91. {
  92. _httpClient.DefaultRequestHeaders.Authorization = null;
  93. await _localStorageService.RemoveItemAsync("authToken");
  94. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  95. }
  96. // throw exception on error response
  97. if (!response.IsSuccessStatusCode)
  98. {
  99. //var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  100. throw new Exception("Error");
  101. }
  102. return await response.Content.ReadAsByteArrayAsync();
  103. }
  104. private async Task<T> sendRequest<T>(HttpRequestMessage request)
  105. {
  106. // add jwt auth header if user is logged in and request is to the api url
  107. try
  108. {
  109. var user = await _localStorageService.GetItemAsync<userToken>("authToken");
  110. var isApiUrl = !request.RequestUri.IsAbsoluteUri;
  111. if (user != null) // && isApiUrl)
  112. {
  113. //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
  114. //將token取出轉為claim
  115. var claims = JwtParser.ParseClaimsFromJwt(user.Token);
  116. //在每次request的header中帶入bearer token
  117. _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
  118. }
  119. }
  120. catch(Exception ex) {
  121. //Console.WriteLine(ex.ToString());
  122. }
  123. using HttpResponseMessage response = await _httpClient.SendAsync(request);
  124. // auto logout on 401 response
  125. if (response.StatusCode == HttpStatusCode.Unauthorized)
  126. {
  127. _httpClient.DefaultRequestHeaders.Authorization = null;
  128. await _localStorageService.RemoveItemAsync("authToken");
  129. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  130. return default;
  131. }
  132. // throw exception on error response
  133. if (!response.IsSuccessStatusCode)
  134. {
  135. var error = await response.Content.ReadFromJsonAsync<string>();
  136. throw new Exception(error);
  137. }
  138. var retData =await response.Content.ReadFromJsonAsync<T>();
  139. return retData;
  140. }
  141. }
  142. }