我创建了一个服务器代码,它通过 post 命令接受文件。 服务器端代码:
app.MapPost("/upload2", async (IFormFile file) =>
{
List<string> validextensions = new List<string>() { ".xlsx" };
string extension = Path.GetExtension(file.FileName);
if (!validextensions.Contains(extension))
{
return $"Extention is not valid({string.Join(",", validextensions)})";
}
string filename = "File1" + extension;
string path = @"D:/";
using FileStream stream = new FileStream(Path.Combine(path, filename), FileMode.Create);
file.CopyToAsync(stream);
return filename;
});
app.MapGet("/GetToken", async (HttpContext context, IAntiforgery antiforgery) =>
{
// Generate the antiforgery token
var tokens = antiforgery.GetAndStoreTokens(context);
var requestToken = tokens.RequestToken;
// Include the token in the response
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(requestToken);
});
我相信这段代码没问题,因为它在邮递员中工作得很好。但是,我通过 C# 发送文件失败!
客户端代码:
public async Task SendExcelFileToServer(string filepath, string filename, string InnerAddress)
{
try
{
// Create an instance of HttpClient
using (var httpClient = new HttpClient())
{
// Set the request URI
string requestUri = ServerAddressTextBox.Text.Trim() + InnerAddress;
// Create multipart form data content
using (var form = new MultipartFormDataContent())
{
string antiforgeryToken, cookie;
(antiforgeryToken, cookie) = await GetAntiforgeryToken();
// Add file part
using (var fileContent = new ByteArrayContent(File.ReadAllBytes(filepath)))
{
//form.Headers.ContentType = MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//form.Add(fileContent, "file", filename);
// This Is obligatory inn .net8! :)
// Add the RequestVerificationToken header
form.Headers.Add("RequestVerificationToken", "CfDJ8IobTqaCf0xCi3hgie2deVpx3DCZeGmVD28L6YAsM51Szh1AF0afHexqh7O768rwdYqOqLx8ph3yM86l7bg_phwtnHFspWVdFBtKScLlooFE_10wA6HidiiMZT6TbqZsR5Q1l6C7qJ9Zcuj_1bhxt10");
// Add the cookie header
form.Headers.Add("Cookie", ".AspNetCore.Antiforgery.p8-WnM9DThg=CfDJ8IobTqaCf0xCi3hgie2deVrgEG5nQyY-SHCgXvPCDh8LFzaqG7fOX41qgeGCXUcjPKgAPvPRqEUgYhzhHLTfcnClNq5rmQIZ-CkycC_V0vzBYhSgXdCVnL_9_ftvHXhYl7S3RR575hPwsAUvKg9D8kQ");
//form.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
//httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
//httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
//httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
// Send post request
HttpResponseMessage response = await httpClient.PostAsync(requestUri, form);
// Check response
response.EnsureSuccessStatusCode();
}
}
}
}
catch
{
MessageBox.Show("Try sending data again and check your connection!");
}
}
我添加了
RequestVerificationToken
手动发送给我的邮递员 post 命令。另外,我将其添加到 C# 中的 post 命令中。虽然Postman命令成功了,但是C# post命令不起作用。
正如您根据我在客户端代码中的注释所看到的,我尝试了很多选项。但他们都失败了。
C# 中服务器对客户端的响应:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1,
Content: System.Net.Http.StreamContent, Headers:
{
Connection: close
Transfer-Encoding: chunked
Date: Wed, 08 May 2024 07:39:44 GMT
Server: Kestrel
Content-Type: text/plain; charset=utf-8
}}
首先,您的客户端示例代码没有在表单中添加文件内容,而仅在表单中添加标题,因此您将向服务器发送一个空表单并当然会收到错误。 (或者你可以删除评论)
form.Add(fileContent, "file", filename);
并且您可以尝试在文件内容而不是表单中添加标头。如果它不起作用,那么这里是一个由 WebApplication 和 HttpClient 完成的上传文件示例。
服务器代码
var app = WebApplication.CreateBuilder(args).Build();
app.MapPost("/upload2", (HttpContext ctx) =>
{
return ctx.Request.Form.Files.First().FileName;
});
app.Run();
客户端代码
var filePath = "./test.xlsx";
var fileName = "test.xlsx";
var requestUri = "http://localhost:5000/upload2";
using var httpClient = new HttpClient();
using var form = new MultipartFormDataContent {
{
new ByteArrayContent(File.ReadAllBytes(filePath)), "file", fileName
}
};
Console.WriteLine(httpClient.PostAsync(requestUri, form).Result);