HttpService.cs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. }
  25. public class HttpService:IHttpService
  26. {
  27. private HttpClient _httpClient;
  28. private NavigationManager _navigationManager;
  29. private ILocalStorageService _localStorageService;
  30. private IConfiguration _configuration;
  31. //private IAuthService _authService;
  32. private AuthenticationStateProvider authenticationStateProvider;
  33. public HttpService(
  34. HttpClient httpClient,
  35. NavigationManager navigationManager,
  36. ILocalStorageService localStorageService,
  37. IConfiguration configuration,
  38. AuthenticationStateProvider authService
  39. )
  40. {
  41. _httpClient = httpClient;
  42. _navigationManager = navigationManager;
  43. _localStorageService = localStorageService;
  44. _configuration = configuration;
  45. authenticationStateProvider = authService;
  46. }
  47. public async Task<T> Get<T>(string uri)
  48. {
  49. var request = new HttpRequestMessage(HttpMethod.Get, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  50. return await sendRequest<T>(request);
  51. }
  52. public async Task<T> Post<T>(string uri, object value)
  53. {
  54. var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
  55. request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
  56. return await sendRequest<T>(request);
  57. }
  58. private async Task<T> sendRequest<T>(HttpRequestMessage request)
  59. {
  60. // add jwt auth header if user is logged in and request is to the api url
  61. try
  62. {
  63. var user = await _localStorageService.GetItemAsync<userToken>("authToken");
  64. var isApiUrl = !request.RequestUri.IsAbsoluteUri;
  65. if (user != null) // && isApiUrl)
  66. {
  67. //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
  68. //將token取出轉為claim
  69. var claims = JwtParser.ParseClaimsFromJwt(user.Token);
  70. //在每次request的header中帶入bearer token
  71. _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
  72. }
  73. }
  74. catch(Exception ex) {
  75. Console.WriteLine(ex.ToString());
  76. }
  77. using HttpResponseMessage response = await _httpClient.SendAsync(request);
  78. // auto logout on 401 response
  79. if (response.StatusCode == HttpStatusCode.Unauthorized)
  80. {
  81. _httpClient.DefaultRequestHeaders.Authorization = null;
  82. await _localStorageService.RemoveItemAsync("authToken");
  83. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  84. return default;
  85. }
  86. // throw exception on error response
  87. if (!response.IsSuccessStatusCode)
  88. {
  89. var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  90. throw new Exception(error["message"]);
  91. }
  92. var retData =await response.Content.ReadFromJsonAsync<T>();
  93. return retData;
  94. }
  95. }
  96. }