private Uri GetResourceUri(RequestInfoEventArgs requestInfo) { var resource = _config.FileUploadResource .Replace("{organisationNumber}", requestInfo.OrganizationNumber) .Replace("{statisticalProgram}", requestInfo.StatisticalProgram) .Replace("{fileFormat}", requestInfo.FileFormat) .Replace("{version}", requestInfo.Version ?? string.Empty); return(new Uri(resource, UriKind.Relative)); }
public async Task <bool> PostFileAsync(RequestInfoEventArgs requestInfo, Stream stream) { // We will create a new client every time to make sure that do not re-use any session cookies. using (var client = _clientFactory.CreateClient(nameof(NetHttpClient))) { var pingResponse = await client.GetAsync(_config.PingResource); if (!pingResponse.IsSuccessStatusCode) { _logger.LogWarning("Heartbeat was not successful. Will abort."); return(false); } // Result from heartbeat isn't used but shown for readability. It should be a DateTime. var pingContent = await pingResponse.Content.ReadAsStringAsync(); byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); ByteArrayContent bytes = new ByteArrayContent(data); var resource = GetResourceUri(requestInfo); _logger.LogDebug($"Will POST file to {client.BaseAddress}/{resource}."); // Set boundary manually. var boundary = Guid.NewGuid().ToString(); MultipartFormDataContent multiContent = new MultipartFormDataContent(boundary); multiContent.Add(bytes, "file", requestInfo.FileName); // HttpClient adds double qoutes (") to the boundary, which is not supported by the server. Therefore we remove them. multiContent.Headers.Remove("Content-Type"); multiContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed; boundary=" + boundary); var response = await client.PostAsync(resource, multiContent); var parsedResponse = await JsonSerializer.DeserializeAsync <FileUploadResponse>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); if (response.IsSuccessStatusCode) { _logger.LogInformation($"File successfully posted. Thank you. The id for your deliveryId is: {parsedResponse.DeliveryId}."); return(true); } _logger.LogError("POST failed."); return(false); } }
public async Task <bool> PostFileAsync(RequestInfoEventArgs requestInfo, Stream stream) { IRestClient client = CreateRestClient(); client.CookieContainer = new CookieContainer(); var heartBeat = new RestRequest(_config.PingResource, Method.GET); var heartBeatUrl = client.BuildUri(heartBeat); // For debugging purposes. _logger.LogDebug($"Will perform a GET to Heartbeat-endpoint using {heartBeatUrl}."); var heartBeatResponse = await client.ExecuteGetAsync(heartBeat); if (!heartBeatResponse.IsSuccessful) { // Possible error handling here. // If you are unable to ping the heartbeat endpoint there's probably // something wrong with the certificate. _logger.LogWarning("Get to Heartbeat-endpoint was not successful. Will abort."); return(false); } _logger.LogDebug("Get to Heartbeat-endpoint was successful."); var cookies = client.CookieContainer.GetCookies(new Uri(_config.BaseUrl)); IRestRequest request = CreateFileUploadRequest(requestInfo, stream); foreach (Cookie restResponseCookie in cookies) { request.AddCookie(restResponseCookie.Name, restResponseCookie.Value); } var url = client.BuildUri(request); _logger.LogInformation($"Posting file to: {url}"); var response = await client.ExecutePostAsync <FileUploadResponse>(request); if (response.StatusCode == HttpStatusCode.OK && response.Data != null) { _logger.LogInformation($"File successfully posted. Thank you. The id for your deliveryId is: {response.Data.DeliveryId}."); // You might want to return the deliveryId for further processing. // For the moment we simply return true to indicate success. return(true); } _logger.LogInformation($"Post failed. Response: {response.ErrorMessage}"); return(false); }
/// <summary> /// Creates a IRestRequest based on a RequestInfoEventArgs /// </summary> /// <param name="requestInfo"></param> /// <param name="stream"></param> /// <returns></returns> private IRestRequest CreateFileUploadRequest(RequestInfoEventArgs requestInfo, Stream stream) { var request = new RestRequest { Resource = _config.FileUploadResource, Method = Method.POST }; request.AddUrlSegment("statisticalProgram", requestInfo.StatisticalProgram); request.AddUrlSegment("fileFormat", requestInfo.FileFormat); request.AddUrlSegment("organisationNumber", requestInfo.OrganizationNumber); request.AddUrlSegment("version", requestInfo.Version ?? string.Empty); byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); request.AddFile("file", data, requestInfo.FileName, "attachment"); return(request); }