WPF call .NET 6 API with Beare Token(Upload file & download file)

[复制链接]
发表于 2026-1-25 20:28:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
HttpClientHelper.cs
  1. using System.IO;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Text;
  5. using Cortland.Shared.Constants;
  6. using System.Net.Http.Headers;
  7. using Newtonsoft.Json;
  8. using System.Configuration;
  9. public partial class HttpClientHelper
  10. {
  11.     #region HTTP POST & GET methods to call APIs in EvanTest
  12.     /// <summary>
  13.     /// Http Post
  14.     /// </summary>
  15.     /// <param name="apiUrl">/api/Requests/SignOff</param>
  16.     /// <param name="postBodyDataJson"></param>
  17.     /// <returns></returns>
  18.     public static string HttpPostWithCookie(string apiUrl, string postBodyDataJson)
  19.     {
  20.         return HttpCallWithCookie(apiUrl, methond: "POST", postBodyDataJson: postBodyDataJson);
  21.     }
  22.     /// <summary>
  23.     /// Http Get
  24.     /// </summary>
  25.     /// <param name="apiUrl"></param>
  26.     /// <returns></returns>
  27.     public static string HttpGetWithCookie(string apiUrl)
  28.     {
  29.         return HttpCallWithCookie(apiUrl, methond: "GET");
  30.     }
  31.     #endregion
  32.     #region Private Functions
  33.     /// <summary>
  34.     /// Http Method to call from EvanTest with Cookies
  35.     /// </summary>
  36.     /// <param name="apiUrl"></param>
  37.     /// <param name="methond">GET OR POST</param>
  38.     /// <param name="postBodyDataJson">Body data,need to convert into Json</param>
  39.     /// <param name="isRelogin"></param>
  40.     /// <param name="contectType">default is "application/json"</param>
  41.     /// <returns></returns>
  42.     private static string HttpCallWithCookie(string apiUrl, string methond = "GET", string postBodyDataJson
  43.         = "", bool isRelogin = true, string contectType = "application/json")
  44.     {
  45.         try
  46.         {
  47.             string baseUrl = GetBaseUrl();
  48.             string url = baseUrl + "/" + apiUrl.TrimStart('/');
  49.             //url = "http://localhost:6634/api/Requests/GetRequestStepsByRequestId?requestId=650";
  50.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  51.             request.Method = methond;
  52.             request.ContentType = contectType;
  53.             request.Accept = contectType;
  54.             #region Check If contained Cookie, if not, will login to EvanTest to get Cookies
  55.             if (string.IsNullOrEmpty(AppConstants.JWTToken) && isRelogin)
  56.             {
  57.                 //check if Cookie is expired. If expired, then login again
  58.                 GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
  59.                 return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
  60.             }
  61.             #endregion
  62.             request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AppConstants.JWTToken);
  63.             //Post with Body Json Data
  64.             if (!string.IsNullOrEmpty(postBodyDataJson))
  65.             {
  66.                 request.ContentLength = postBodyDataJson.Length;
  67.                 StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
  68.                 writer.Write(postBodyDataJson);
  69.                 writer.Flush();
  70.             }
  71.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  72.             if (response.StatusCode == HttpStatusCode.OK)
  73.             {
  74.                 string encoding = response.ContentEncoding;
  75.                 if (encoding == null || encoding.Length < 1)
  76.                 {
  77.                     encoding = "UTF-8";
  78.                 }
  79.                 //AppConstants.CookieValue = GetCookie(response);
  80.                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
  81.                 string retString = reader.ReadToEnd();
  82.                 bool isCookieExpired = IsCookieExpired(retString);
  83.                 if (isRelogin && isCookieExpired)//This means token expired, will relogin and call API again
  84.                 {
  85.                     //check if Cookie is expired. If expired, then login again
  86.                     GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
  87.                     if (!string.IsNullOrEmpty(AppConstants.JWTToken))
  88.                     {
  89.                         return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
  90.                     }
  91.                 }
  92.                 return retString;
  93.             }
  94.             else if (isRelogin)
  95.             {
  96.                 //check if Cookie is expired. If expired, then login again
  97.                 GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
  98.                 if (!string.IsNullOrEmpty(AppConstants.JWTToken))
  99.                 {
  100.                     return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
  101.                 }
  102.             }
  103.             return null;
  104.         }
  105.         catch (Exception ex)
  106.         {
  107.             throw new Exception($"(EvanTest) Call API {apiUrl} failed. " + ex.Message);
  108.         }
  109.     }
  110.     /// <summary>
  111.     /// Check Cookie if expired.
  112.     /// If return HTML that means expired
  113.     /// </summary>
  114.     /// <param name="retString"></param>
  115.     /// <returns></returns>
  116.     private static bool IsCookieExpired(string retString)
  117.     {
  118.         return retString != null && retString.Contains("<!DOCTYPE html>");
  119.     }
  120.     private static string GetCookieForHttpHeader(HttpResponseMessage message)
  121.     {
  122.         string cookieString = string.Empty;
  123.         message.Headers.TryGetValues("Set-Cookie", out var setCookie);
  124.         if (setCookie != null)
  125.         {
  126.             cookieString = string.Join(";", setCookie);
  127.         }
  128.         return cookieString;
  129.     }
  130.     #endregion
  131.     private static HttpClientHandler GenerateHttpClientHandler(string apiUrl)
  132.     {
  133.         // HttpClientHandler
  134.         // helpLink https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler?view=netframework-4.8
  135.         var httpclientHandler = new HttpClientHandler();
  136.         // Skip https certificate validation
  137.         if (apiUrl.StartsWith("https"))
  138.         {
  139.             httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
  140.         }
  141.         return httpclientHandler;
  142.     }
  143.    private static string GetBaseUrl()
  144.    {
  145.        string? baseUrl = ConfigurationManager.AppSettings["AgencyCorproUrl"];
  146.        if (baseUrl != null)
  147.        {
  148.            return baseUrl.TrimEnd('/');
  149.        }
  150.        return string.Empty;
  151.    }
  152.     public static string GetAgencyCorProToken(string userName, string password, int crmUserId)
  153.     {
  154.         string tokenValue = "";
  155.         try
  156.         {
  157.             string baseUrl = GetBaseUrl();
  158.             if (!string.IsNullOrEmpty(baseUrl))
  159.             {
  160.                 string authenticateUrl = CorProAPI.AUTHENTICATE_TOKEN_URL;
  161.                 LoginModelParameter loginModel = GetParameter(userName, password, crmUserId);
  162.                 HttpClient httpClient = new HttpClient();
  163.                 HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(baseUrl + authenticateUrl, loginModel).Result;
  164.                 if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
  165.                 {
  166.                     UserAccessTokenDto userAccessToken = httpResponseMessage.Content.ReadAsAsync<UserAccessTokenDto>().Result;
  167.                     if (userAccessToken != null)
  168.                     {
  169.                         tokenValue = userAccessToken.Token;
  170.                         AppConstants.JWTToken = tokenValue;
  171.                     }
  172.                 }
  173.                 httpClient.Dispose();
  174.             }
  175.         }
  176.         catch (Exception ex)
  177.         {
  178.             throw;
  179.         }
  180.         return tokenValue;
  181.     }
  182.     public static void DownloadDocument(int documentId, string saveFileName, bool isDownloadDocument = true)
  183.     {
  184.         try
  185.         {
  186.             string baseUrl = GetBaseUrl();
  187.             if (!string.IsNullOrEmpty(baseUrl))
  188.             {
  189.                 DownloadParameter downloadParameter = new DownloadParameter();
  190.                 downloadParameter.Token = AppConstants.JWTToken;
  191.                 downloadParameter.DocumentId = documentId;
  192.                 string apiUrl = $"{baseUrl}{CorProAPI.DOWNLOAD_BORROWING_REQUEST_DOCUMENT_URL}";
  193.                 var httpclientHandler = GenerateHttpClientHandler(apiUrl);
  194.                 using (var httpClient = new HttpClient(httpclientHandler))
  195.                 {
  196.                     // Bearer
  197.                     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConstants.JWTToken);
  198.                     HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(apiUrl, downloadParameter).Result;
  199.                     if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
  200.                     {
  201.                         Stream stream = httpResponseMessage.Content.ReadAsStreamAsync().Result;
  202.                         using (var filestream = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
  203.                         {
  204.                             stream.CopyTo(filestream);
  205.                         }
  206.                         stream.Close();
  207.                     }
  208.                     httpClient.Dispose();
  209.                 }
  210.             }
  211.         }
  212.         catch (Exception ex)
  213.         {
  214.             throw new Exception($"(CorPro Agency) Call API {CorProAPI.DOWNLOAD_BORROWING_REQUEST_DOCUMENT_URL} failed. " + ex.Message);
  215.         }
  216.     }
  217.         /// <summary>
  218. /// upload docuemnt
  219. /// </summary>
  220. /// <param name="UploadDocumentDto"></param>
  221. /// <returns></returns>
  222. /// <exception cref="Exception"></exception>
  223. public static UploadDocumentDto InsertOrUpdateDocument(UploadDocumentDto UploadDocumentDto)
  224. {
  225.      try
  226.      {
  227.          UploadDocumentDto borrowingRequestCommentDtoNew = UploadDocumentDto;
  228.          string baseUrl = GetBaseUrl();
  229.          if (!string.IsNullOrEmpty(baseUrl))
  230.          {
  231.              string apiUrl = $"{baseUrl}{CorProAPI.INSERT_UPDATE_BORROWING_REQUEST_DOCUMENT}";
  232.              var httpclientHandler = GenerateHttpClientHandler(apiUrl);
  233.              HttpClient httpClient = new HttpClient(httpclientHandler);
  234.              httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConstants.JWTToken);
  235.              HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(apiUrl, UploadDocumentDto).Result;
  236.              if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
  237.              {
  238.                  borrowingRequestCommentDtoNew = httpResponseMessage.Content.ReadAsAsync<UploadDocumentDto>().Result;
  239.              }
  240.              httpClient.Dispose();
  241.          }
  242.          return borrowingRequestCommentDtoNew;
  243.      }
  244.      catch (Exception ex)
  245.      {
  246.          throw new Exception($"(CorPro Agency) Call API {CorProAPI.INSERT_UPDATE_BORROWING_REQUEST_DOCUMENT} failed. " + ex.Message);
  247.      }
  248. }
  249. }
  250. public class LoginModelParameter
  251. {
  252.     public string Token { get; set; }
  253. }
  254. public class DownloadParameter : LoginModelParameter
  255. {
  256.     public int DocumentId { get; set; }
  257. }
  258. public class UploadDocumentDto
  259. {
  260.     public int Id { get; set; }
  261.     public int BorrowingRequestId { get; set; }
  262.     public string FileName { get; set; }
  263.     public string UploadFilePath { get; set; }
  264.     /// <summary>
  265.     /// Save file to webservice use (Docs/1d848a6e493b46c191180fe171b2492f.pdf)
  266.     /// </summary>
  267.     public string ServerUploadFilePath { get; set; }
  268.     /// <summary>
  269.     /// Save file to webservice use  (1d848a6e493b46c191180fe171b2492f.pdf)
  270.     /// </summary>
  271.     public string ServerUploadFileName { get; set; }
  272.     /// <summary>
  273.     /// CRMUserId, query data from ApplicationUsers or MCP2 table
  274.     /// </summary>
  275.     public int CreatorUserId { get; set; }
  276.     /// <summary>
  277.     /// UTC time
  278.     /// </summary>
  279.     public DateTime CreationTime { get; set; }
  280.     public string Comment { get; set; }
  281.     public decimal? FileSize { get; set; }
  282.     public string FileSizeUnit { get; set; }
  283.     /// <summary>
  284.     /// Not Yet
  285.     /// </summary>
  286.     public string CreatorUserName { get; set; }
  287.     public byte[] UploadFiles { get; set; }
  288.     public string UserTokenValue { get; set; }
  289.     public string NewFileName { get; set; }
  290.     public string SelectedFileName { get; set; }
  291.     public string ShowFileNameAndFileSize
  292.     {
  293.         get
  294.         {
  295.             string newFileName = "";
  296.             if (!string.IsNullOrEmpty(FileName))
  297.             {
  298.                 newFileName = FileName;
  299.                 if (FileSize.HasValue && FileSize.Value > 0 && !string.IsNullOrEmpty(FileSizeUnit))
  300.                 {
  301.                     newFileName += " " + FileSize.Value.ToString("0.00") + FileSizeUnit;
  302.                 }
  303.             }
  304.             return newFileName;
  305.         }
  306.     }
  307.     public ActivityRequestEnumType? RequestType { get; set; }
  308.     public int? CreateBorrowingRequestUserId { get; set; }
  309. }
复制代码
Upload file
  1.        private void AddCommentBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  2.        {
  3.            BorrowingRequestDocumentDto borrowingRequestDocumentDto = e.Argument as BorrowingRequestDocumentDto;
  4.            if (!string.IsNullOrEmpty(borrowingRequestDocumentDto.SelectedFileName))
  5.            {
  6.                IsDownloading = true;
  7.                System.IO.FileInfo fileInfo = new System.IO.FileInfo(borrowingRequestDocumentDto.SelectedFileName);
  8.                borrowingRequestDocumentDto.FileName = fileInfo.Name;
  9.                borrowingRequestDocumentDto.NewFileName = Guid.NewGuid().ToString() + fileInfo.Extension;
  10.                borrowingRequestDocumentDto.UploadFiles = FileUtil.ConvertFileToBytes(borrowingRequestDocumentDto.SelectedFileName);
  11.            }
  12.            if (borrowingRequestDocumentDto != null)
  13.            {
  14.                e.Result = HttpClientHelper.InsertOrUpdateDocument(borrowingRequestDocumentDto);
  15.            }
  16.        }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表