Ich habe versucht herauszufinden, warum ich meine Azure -Funktion lokal ausführen kann und die Datei korrekt heruntergeladen wird. Aber wenn ich es in meiner Testumgebung als Azure -Funktion einsuche, gelingt es immer noch und ich erhalte eine 200 -OK -Antwort, aber die Dateigröße ist nicht die gleiche und ich kann sie nicht öffnen - ich gehe davon aus, dass sie korrupt ist. Ich habe mehr Protokollierung hinzugefügt, kann aber immer noch nicht herausfinden, was los ist. Die Funktion kann auf die Website zugreifen, erfolgreich anmelden und (einige) der Datei herunterladen. Hinweis: Meine Azure -Funktion nimmt ein FileUrl -String -Array im Körper ein und ich möchte ein String -Array von Dateinamen zurückgeben. < /P>
[Function("DownloadPng")]
public async Task Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest httpRequest)
{
this.log.LogInformation("Download png start.");
try
{
string requestBody = await new StreamReader(httpRequest.Body).ReadToEndAsync();
this.log.LogInformation("Request body read successfully.");
Request? request = JsonConvert.DeserializeObject(requestBody);
if (request?.FileUrls == null)
{
this.log.LogError("Invalid request body: FileUrls is null.");
return new BadRequestObjectResult("Please pass valid file URLs in the request body.");
}
List fileUrls = request.FileUrls.Split(',').ToList();
this.log.LogInformation($"Parsed {fileUrls.Count} file URLs from request body.");
if (!fileUrls.Any())
{
this.log.LogError("No file URLs found in the request body.");
return new BadRequestObjectResult("No file URLs in the request body.");
}
var loginUrl = Environment.GetEnvironmentVariable("Url");
var username = Environment.GetEnvironmentVariable("Username");
var password = Environment.GetEnvironmentVariable("Password");
if (string.IsNullOrEmpty(loginUrl) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
this.log.LogError("Environment variables for login are not set.");
return new BadRequestObjectResult("Environment variables for login are not set.");
}
this.log.LogInformation("Attempting to retrieve request verification token.");
var token = await this.GetRequestVerificationTokenAsync(loginUrl);
if (string.IsNullOrEmpty(token))
{
this.log.LogError("Failed to retrieve the __RequestVerificationToken.");
return new BadRequestObjectResult("Failed to retrieve the __RequestVerificationToken.");
}
this.log.LogInformation("Attempting to log in.");
var loginSuccess = await this.LoginAsync(loginUrl, username, password, token);
if (!loginSuccess)
{
this.log.LogError("Login failed.");
return new BadRequestObjectResult("Login failed.");
}
this.log.LogInformation("Login successful!");
List pngBlobsList = new List();
foreach (var fileUrl in fileUrls)
{
this.log.LogInformation($"Downloading file from URL: {fileUrl}");
var fileName = await this.DownloadAndSaveFileAsync(fileUrl);
pngBlobsList.Add(fileName);
}
this.log.LogInformation("Download png completed successfully.");
return new OkObjectResult(pngBlobsList);
}
catch (Exception ex)
{
this.log.LogError(ex, "An error occurred - {0}", ex.Message);
return new StatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
private async Task DownloadAndSaveFileAsync(string fileUrl)
{
this.log.LogInformation("Starting download of file from URL: {FileUrl}", fileUrl);
try
{
// Send GET request to download the file
using var response = await Client.GetAsync(fileUrl, HttpCompletionOption.ResponseHeadersRead);
if (!response.IsSuccessStatusCode)
{
this.log.LogError("Failed to download file from {FileUrl}. Status code: {StatusCode}", fileUrl, response.StatusCode);
throw new HttpRequestException($"Failed to download file from {fileUrl}. Status code: {response.StatusCode}");
}
this.log.LogInformation("File downloaded successfully from {FileUrl}", fileUrl);
// Read the file content into a memory stream
using var memoryStream = new MemoryStream();
await response.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0;
this.log.LogInformation("Downloaded file size: {Size} bytes", memoryStream.Length);
// Generate a unique file name for the blob
string fileName = Guid.NewGuid().ToString() + ".png";
BlobDetails blobDetails = this.blobStorageManager.CreateBlobWithWriteToken(fileName);
if (string.IsNullOrEmpty(blobDetails.BlobUrl))
{
this.log.LogError("Blob upload failed for {FileUrl}. Blob URL: {BlobUrl}, SAS Token: {SasToken}", fileUrl, blobDetails.BlobUrl, blobDetails.SasToken);
throw new ArgumentNullException(nameof(blobDetails.BlobUrl), "Blob URL cannot be null or empty");
}
this.log.LogInformation("Uploading file to Azure Blob Storage with name {FileName}", fileName);
// Save the file to Azure Blob Storage
await this.blobStorageManager.SaveToBlobStorageAsync(blobDetails.BlobUrl + blobDetails.SasToken, memoryStream.ToArray());
this.log.LogInformation("File uploaded successfully to Azure Blob Storage: {BlobUrl}", blobDetails.BlobUrl);
return fileName;
}
catch (Exception ex)
{
this.log.LogError(ex, "An error occurred while downloading or saving the file from {FileUrl}", fileUrl);
throw;
}
}
< /code>
Gibt es eine Anleitung, wie ich dieses Problem debuggen kann? Es wäre sehr geschätzt.
Versuchen Sie, eine Datei von der externen Website mit C# Azure -Funktion herunterzuladen ⇐ C#
-
- Similar Topics
- Replies
- Views
- Last post