HttpService.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. _navigationManager = navigationManager;
  44. _localStorageService = localStorageService;
  45. _configuration = configuration;
  46. authenticationStateProvider = authService;
  47. }
  48. public async Task<T> Get<T>(string uri)
  49. {
  50. var request = new HttpRequestMessage(HttpMethod.Get, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  51. return await sendRequest<T>(request);
  52. }
  53. public async Task<T> Post<T>(string uri, object value)
  54. {
  55. var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  56. request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
  57. return await sendRequest<T>(request);
  58. }
  59. public async Task<byte[]> Post(string uri, object value)
  60. {
  61. var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  62. //request.Headers.Add("Content-Type", "application/json");
  63. request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
  64. var data =await snedRequestNotReturn(request);
  65. return data;
  66. }
  67. private async Task<byte[]> snedRequestNotReturn(HttpRequestMessage request)
  68. {
  69. // add jwt auth header if user is logged in and request is to the api url
  70. try
  71. {
  72. var user = await _localStorageService.GetItemAsync<userToken>("authToken");
  73. var isApiUrl = !request.RequestUri.IsAbsoluteUri;
  74. if (user != null) // && isApiUrl)
  75. {
  76. //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
  77. //將token取出轉為claim
  78. var claims = JwtParser.ParseClaimsFromJwt(user.Token);
  79. //在每次request的header中帶入bearer token
  80. _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. //Console.WriteLine(ex.ToString());
  86. }
  87. using HttpResponseMessage response = await _httpClient.SendAsync(request);
  88. // auto logout on 401 response
  89. if (response.StatusCode == HttpStatusCode.Unauthorized)
  90. {
  91. _httpClient.DefaultRequestHeaders.Authorization = null;
  92. await _localStorageService.RemoveItemAsync("authToken");
  93. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  94. }
  95. // throw exception on error response
  96. if (!response.IsSuccessStatusCode)
  97. {
  98. //var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  99. throw new Exception("Error");
  100. }
  101. return await response.Content.ReadAsByteArrayAsync();
  102. }
  103. private async Task<T> sendRequest<T>(HttpRequestMessage request)
  104. {
  105. // add jwt auth header if user is logged in and request is to the api url
  106. try
  107. {
  108. var user = await _localStorageService.GetItemAsync<userToken>("authToken");
  109. var isApiUrl = !request.RequestUri.IsAbsoluteUri;
  110. if (user != null) // && isApiUrl)
  111. {
  112. //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
  113. //將token取出轉為claim
  114. var claims = JwtParser.ParseClaimsFromJwt(user.Token);
  115. //在每次request的header中帶入bearer token
  116. _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
  117. }
  118. }
  119. catch(Exception ex) {
  120. //Console.WriteLine(ex.ToString());
  121. }
  122. using HttpResponseMessage response = await _httpClient.SendAsync(request);
  123. // auto logout on 401 response
  124. if (response.StatusCode == HttpStatusCode.Unauthorized)
  125. {
  126. _httpClient.DefaultRequestHeaders.Authorization = null;
  127. await _localStorageService.RemoveItemAsync("authToken");
  128. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  129. return default;
  130. }
  131. // throw exception on error response
  132. if (!response.IsSuccessStatusCode)
  133. {
  134. var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  135. throw new Exception(error["message"]);
  136. }
  137. var retData =await response.Content.ReadFromJsonAsync<T>();
  138. return retData;
  139. }
  140. }
  141. }