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

HttpClientHelper.cs

using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using Cortland.Shared.Constants;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Configuration;

 public partial class HttpClientHelper
{
    #region HTTP POST & GET methods to call APIs in EvanTest

    /// <summary>
    /// Http Post
    /// </summary>
    /// <param name="apiUrl">/api/Requests/SignOff</param>
    /// <param name="postBodyDataJson"></param>
    /// <returns></returns>
    public static string HttpPostWithCookie(string apiUrl, string postBodyDataJson)
    {
        return HttpCallWithCookie(apiUrl, methond: "POST", postBodyDataJson: postBodyDataJson);
    }

    /// <summary>
    /// Http Get
    /// </summary>
    /// <param name="apiUrl"></param>
    /// <returns></returns>
    public static string HttpGetWithCookie(string apiUrl)
    {
        return HttpCallWithCookie(apiUrl, methond: "GET");
    }
    #endregion


    #region Private Functions

    /// <summary>
    /// Http Method to call from EvanTest with Cookies
    /// </summary>
    /// <param name="apiUrl"></param>
    /// <param name="methond">GET OR POST</param>
    /// <param name="postBodyDataJson">Body data,need to convert into Json</param>
    /// <param name="isRelogin"></param>
    /// <param name="contectType">default is "application/json"</param>
    /// <returns></returns>
    private static string HttpCallWithCookie(string apiUrl, string methond = "GET", string postBodyDataJson
        = "", bool isRelogin = true, string contectType = "application/json")
    {
        try
        {
            string baseUrl = GetBaseUrl();
            string url = baseUrl + "/" + apiUrl.TrimStart('/');
            //url = "http://localhost:6634/api/Requests/GetRequestStepsByRequestId?requestId=650";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = methond;
            request.ContentType = contectType;
            request.Accept = contectType;

            #region Check If contained Cookie, if not, will login to EvanTest to get Cookies

            if (string.IsNullOrEmpty(AppConstants.JWTToken) && isRelogin)
            {
                //check if Cookie is expired. If expired, then login again
                GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
                return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
            }

            #endregion

            request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AppConstants.JWTToken);

            //Post with Body Json Data
            if (!string.IsNullOrEmpty(postBodyDataJson))
            {
                request.ContentLength = postBodyDataJson.Length;
                StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                writer.Write(postBodyDataJson);
                writer.Flush();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8";
                }
                //AppConstants.CookieValue = GetCookie(response);
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string retString = reader.ReadToEnd();
                bool isCookieExpired = IsCookieExpired(retString);
                if (isRelogin && isCookieExpired)//This means token expired, will relogin and call API again
                {
                    //check if Cookie is expired. If expired, then login again
                    GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
                    if (!string.IsNullOrEmpty(AppConstants.JWTToken))
                    {
                        return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
                    }
                }
                return retString;
            }
            else if (isRelogin)
            {
                //check if Cookie is expired. If expired, then login again
                GetAgencyCorProToken(AppConstants.Relogin_CurrentUserName, AppConstants.Relogin_UserPwd, AppConstants.AgencyCorProCrmUserId);
                if (!string.IsNullOrEmpty(AppConstants.JWTToken))
                {
                    return HttpCallWithCookie(apiUrl, methond, postBodyDataJson, isRelogin: false, contectType);
                }
            }
            return null;
        }
        catch (Exception ex)
        {
            throw new Exception($"(EvanTest) Call API {apiUrl} failed. " + ex.Message);
        }
    }

    /// <summary>
    /// Check Cookie if expired.
    /// If return HTML that means expired
    /// </summary>
    /// <param name="retString"></param>
    /// <returns></returns>
    private static bool IsCookieExpired(string retString)
    {
        return retString != null && retString.Contains("<!DOCTYPE html>");
    }

    private static string GetCookieForHttpHeader(HttpResponseMessage message)
    {
        string cookieString = string.Empty;
        message.Headers.TryGetValues("Set-Cookie", out var setCookie);
        if (setCookie != null)
        {
            cookieString = string.Join(";", setCookie);
        }
        return cookieString;
    }

    #endregion


    private static HttpClientHandler GenerateHttpClientHandler(string apiUrl)
    {
        // HttpClientHandler
        // helpLink https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler?view=netframework-4.8
        var httpclientHandler = new HttpClientHandler();

        // Skip https certificate validation
        if (apiUrl.StartsWith("https"))
        {
            httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
        }

        return httpclientHandler;
    }

   private static string GetBaseUrl()
   {
       string? baseUrl = ConfigurationManager.AppSettings["AgencyCorproUrl"];
       if (baseUrl != null)
       {
           return baseUrl.TrimEnd('/');
       }
       return string.Empty;
   }


    public static string GetAgencyCorProToken(string userName, string password, int crmUserId)
    {
        string tokenValue = "";
        try
        {
            string baseUrl = GetBaseUrl();
            if (!string.IsNullOrEmpty(baseUrl))
            {
                string authenticateUrl = CorProAPI.AUTHENTICATE_TOKEN_URL;
                LoginModelParameter loginModel = GetParameter(userName, password, crmUserId);
                HttpClient httpClient = new HttpClient();
                HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(baseUrl + authenticateUrl, loginModel).Result;
                if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
                {
                    UserAccessTokenDto userAccessToken = httpResponseMessage.Content.ReadAsAsync<UserAccessTokenDto>().Result;
                    if (userAccessToken != null)
                    {
                        tokenValue = userAccessToken.Token;
                        AppConstants.JWTToken = tokenValue;
                    }
                }
                httpClient.Dispose();
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        return tokenValue;
    }


    public static void DownloadDocument(int documentId, string saveFileName, bool isDownloadDocument = true)
    {
        try
        {
            string baseUrl = GetBaseUrl();
            if (!string.IsNullOrEmpty(baseUrl))
            {
                DownloadParameter downloadParameter = new DownloadParameter();

                downloadParameter.Token = AppConstants.JWTToken;
                downloadParameter.DocumentId = documentId;


                string apiUrl = $"{baseUrl}{CorProAPI.DOWNLOAD_BORROWING_REQUEST_DOCUMENT_URL}";

                var httpclientHandler = GenerateHttpClientHandler(apiUrl);
                using (var httpClient = new HttpClient(httpclientHandler))
                {
                    // Bearer
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConstants.JWTToken);
                    HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(apiUrl, downloadParameter).Result;
                    if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        Stream stream = httpResponseMessage.Content.ReadAsStreamAsync().Result;
                        using (var filestream = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
                        {
                            stream.CopyTo(filestream);
                        }
                        stream.Close();
                    }
                    httpClient.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception($"(CorPro Agency) Call API {CorProAPI.DOWNLOAD_BORROWING_REQUEST_DOCUMENT_URL} failed. " + ex.Message);
        }
    }


        /// <summary>
 /// upload docuemnt
 /// </summary>
 /// <param name="UploadDocumentDto"></param>
 /// <returns></returns>
 /// <exception cref="Exception"></exception>
 public static UploadDocumentDto InsertOrUpdateDocument(UploadDocumentDto UploadDocumentDto)
 {
     try
     {
         UploadDocumentDto borrowingRequestCommentDtoNew = UploadDocumentDto;
         string baseUrl = GetBaseUrl();
         if (!string.IsNullOrEmpty(baseUrl))
         {
             string apiUrl = $"{baseUrl}{CorProAPI.INSERT_UPDATE_BORROWING_REQUEST_DOCUMENT}";

             var httpclientHandler = GenerateHttpClientHandler(apiUrl);
             HttpClient httpClient = new HttpClient(httpclientHandler);
             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConstants.JWTToken);

             HttpResponseMessage httpResponseMessage = httpClient.PostAsJsonAsync(apiUrl, UploadDocumentDto).Result;
             if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
             {
                 borrowingRequestCommentDtoNew = httpResponseMessage.Content.ReadAsAsync<UploadDocumentDto>().Result;
             }
             httpClient.Dispose();
         }
         return borrowingRequestCommentDtoNew;
     }
     catch (Exception ex)
     {
         throw new Exception($"(CorPro Agency) Call API {CorProAPI.INSERT_UPDATE_BORROWING_REQUEST_DOCUMENT} failed. " + ex.Message);
     }
 }

}

public class LoginModelParameter
{

    public string Token { get; set; }

}
public class DownloadParameter : LoginModelParameter
{
    public int DocumentId { get; set; }
}


public class UploadDocumentDto
{
    public int Id { get; set; }

    public int BorrowingRequestId { get; set; }

    public string FileName { get; set; }

    public string UploadFilePath { get; set; }

    /// <summary>
    /// Save file to webservice use (Docs/1d848a6e493b46c191180fe171b2492f.pdf)
    /// </summary>
    public string ServerUploadFilePath { get; set; }

    /// <summary>
    /// Save file to webservice use  (1d848a6e493b46c191180fe171b2492f.pdf)
    /// </summary>
    public string ServerUploadFileName { get; set; }

    /// <summary>
    /// CRMUserId, query data from ApplicationUsers or MCP2 table
    /// </summary>
    public int CreatorUserId { get; set; }

    /// <summary>
    /// UTC time
    /// </summary>
    public DateTime CreationTime { get; set; }

    public string Comment { get; set; }

    public decimal? FileSize { get; set; }

    public string FileSizeUnit { get; set; }

    /// <summary>
    /// Not Yet
    /// </summary>
    public string CreatorUserName { get; set; }

    public byte[] UploadFiles { get; set; }

    public string UserTokenValue { get; set; }

    public string NewFileName { get; set; }

    public string SelectedFileName { get; set; }

    public string ShowFileNameAndFileSize
    {
        get
        {
            string newFileName = "";
            if (!string.IsNullOrEmpty(FileName))
            {
                newFileName = FileName;
                if (FileSize.HasValue && FileSize.Value > 0 && !string.IsNullOrEmpty(FileSizeUnit))
                {
                    newFileName += " " + FileSize.Value.ToString("0.00") + FileSizeUnit;
                }
            }
            return newFileName;
        }
    }

    public ActivityRequestEnumType? RequestType { get; set; }

    public int? CreateBorrowingRequestUserId { get; set; }
}

Upload file

       private void AddCommentBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
       {
           BorrowingRequestDocumentDto borrowingRequestDocumentDto = e.Argument as BorrowingRequestDocumentDto;
           if (!string.IsNullOrEmpty(borrowingRequestDocumentDto.SelectedFileName))
           {
               IsDownloading = true;
               System.IO.FileInfo fileInfo = new System.IO.FileInfo(borrowingRequestDocumentDto.SelectedFileName);
               borrowingRequestDocumentDto.FileName = fileInfo.Name;
               borrowingRequestDocumentDto.NewFileName = Guid.NewGuid().ToString() + fileInfo.Extension;
               borrowingRequestDocumentDto.UploadFiles = FileUtil.ConvertFileToBytes(borrowingRequestDocumentDto.SelectedFileName);
           }
           if (borrowingRequestDocumentDto != null)
           {
               e.Result = HttpClientHelper.InsertOrUpdateDocument(borrowingRequestDocumentDto);
           }
       }

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值