C#测试文件上传

jen*_*gar 2 c# nunit asp.net-web-api owin

我浏览了各种帖子并尝试了几件事但我无法让事情正常进行.我不觉得应该那么难,但这就是我得到的.我只想将文件发布到我的服务器以进行测试.它应该像我从<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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

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());
}
Run Code Online (Sandbox Code Playgroud)

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

Vea*_*tch 5

问题是,HttpContext.Current您正在进行的自托管测试中无法使用该问题.

看看这里:

HttpSelfHostServer和HttpContext.Current