gpt4 book ai didi

C# 测试文件上传

转载 作者:行者123 更新时间:2023-11-30 19:57:24 24 4
gpt4 key购买 nike

我浏览了各种帖子并尝试了一些方法,但我一直无法正常工作。我不觉得应该那么难,但这就是我得到的。我只是想将文件发布到我的服务器以进行测试。它应该像我从标准 <input type="file"/> 上传它一样工作在网页上。

这是我要测试的实际处理程序:

[Route("MyAction")]
[HttpPost]
public IHttpActionResult MyAction()
{
try
{
var request = HttpContext.Current.Request;
if (request.Files.Count == 1)
{
var postedFile = request.Files[0];
if (request.Files[0].FileName.EndsWith(".zip"))
{
// unzip the file
// do stuff
}
}
}
catch
{
return new ValidationError("An error has occurred and has been logged");
}
}

这是我的测试:

public void SetupServer()
{
server = TestServer.Create(app =>
{
var startup = new Startup();
startup.ConfigureOAuth(app);

var config = new HttpConfiguration();
WebApiConfig.Register(config);

app.UseWebApi(config);
});
}


[Test]
public async Task MyActionTest()
{
SetupServer();
Uri = "/api/myClass/myRoute";

var file = Properties.Resources.myZipFile;

var boundary = "------------------------" + DateTime.Now.Ticks;

var multipartFileContent = new MultipartFormDataContent(boundary);
var content = new ByteArrayContent(file);
content.Headers.Add("Content-Type", "application/octet-stream");
multipartFileContent.Add(content, "myFileName", "myZipFile.zip");

var serverResp = (await server.CreateRequest(Uri)
.And(req => req.Content = multipartFileContent)
.PostAsync());
}

运行此测试会在 var request = HttpContext.Current.Request; 上导致错误因为HttpContext.Current由于某种原因为空。我是不是以错误或艰难的方式来解决这个问题?我觉得不应该这么难。

最佳答案

问题是 HttpContext.Current 在您正在启动的自托管测试中不可用。

看这里:

HttpSelfHostServer and HttpContext.Current

关于C# 测试文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com