简体   繁体   English

如何使用TestServer和Antiforgery修复POST集成测试中的500 Internal Server Error? ASP.NET核心

[英]How to fix 500 Internal Server Error for POST integration tests using TestServer and Antiforgery? ASP.NET Core

I've got a working ASP.NET Core 2.2 implementation that utilizes both MVC and API controllers, and I'm putting together an integration test project to cover everything that has already been tested manually - the basic crud, mostly. 我有一个使用MVC和API控制器的有效的ASP.NET Core 2.2实现,并且我将一个集成测试项目组合在一起,以涵盖已经进行了手动测试的所有内容-主要是基本内容。 Everything works except the tests that use PostAsync to POST data. 除了使用PostAsync来发布数据的测试之外,其他所有功能都可以正常工作。 These tests always get a 500 Internal Server Error as a response from the client, and I cannot for the life of me figure out why. 这些测试始终会从客户端获得500内部服务器错误作为响应,而我一生都无法弄清原因。 Oi! 喂!

The TestServer setup is a pretty standard approach that I've seen on many different blogs and articles. 我在许多不同的博客和文章中都看到过TestServer设置是一种非常标准的方法。 A TestStartup class extends the standard Startup, and overrides the configuration to use in-memory database with seed data. TestStartup类扩展了标准的Startup,并覆盖了配置以将内存数据库与种子数据一起使用。 My test fixture base then uses the TestStartup to create a server, and a client, and has a method, which I know works fine, to extract the antiforgery token and add it to forms and headers. 然后,我的测试夹具库使用TestStartup创建服务器和客户端,并具有一个我知道可以正常工作的方法,以提取防伪令牌并将其添加到表单和标头中。 All other tests verifying all other aspects of CRUD are working, proving that the seeded data can be retrieved, via both MVC and API calls. 验证CRUD的所有其他方面的所有其他测试都正常工作,证明可以通过MVC和API调用来检索种子数据。

The POST calls that eventually fail with a 500 Internal Server Error do make it into the controller, and the subsequent repository, just fine. 最终因500 Internal Server Error(内部服务器错误)而失败的POST调用确实使它进入了控制器以及后续的存储库,就可以了。 With all these aspects in place, I've yet to be able to see the source of the 500. 有了所有这些方面之后,我还无法看到500的来源。

    [Fact]
    public async void CreatePost_ShouldReturnViewWithNewlyCreatedLabelData()
    {
        // Arrange
        var formData = await EnsureAntiForgeryTokenOnForm(new Dictionary<string, string>()
        {
            { "Name", TestDataGraph.Labels.LabelNew.Name },
            { "WebsiteUrl", TestDataGraph.Labels.LabelNew.WebsiteUrl }
        });

        // Act
        var response = await Client.PostAsync("/labels/create", new FormUrlEncodedContent(formData));

        // Assert
        Assert.Equal(HttpStatusCode.Found, response.StatusCode);
        Assert.Equal("/Labels", response.Headers.Location.ToString());
    }

This is a simple example test in Xunit that attempts to validate the creation of a new simple object, type Label, via MVC route, which follows the standard path format, having been scaffolded. 这是Xunit中的一个简单示例测试,试图通过MVC路由验证遵循标准路径格式的新简单对象类型Label的创建,该方法已被搭建好。 This test will make it into the controller, and its repository, but the response will be a 500 Internal Server Error. 该测试会将其放入控制器及其存储库中,但是响应将是500 Internal Server Error。

Could I have missed something important in Startup? 我会错过启动中的重要内容吗? Any ideas for finding further details about this failure? 有什么想法可以找到有关此故障的更多详细信息? Thanks in advance! 提前致谢! I can post more code or details if they will be helpful. 如果有帮助,我可以发布更多代码或详细信息。

Try adding trace logging... Trace logging will display activity in the .Net Core framework. 尝试添加跟踪日志记录...跟踪日志记录将在.Net Core框架中显示活动。

...
public static ILogger<ConsoleLoggerProvider> AppLogger = null;
public static ILoggerFactory loggerFactory = null;
//
public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(builder => builder
        .AddConsole()
        .AddFilter(level => level >= LogLevel.Trace)
    );
    loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>();
    AppLogger = loggerFactory.CreateLogger<ConsoleLoggerProvider>();
    ...

An example trace log: 跟踪日志示例:

trce: Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler[7]
    Could not find a file for view at path '/Views/Home/_Layout.cshtml'.

After you have resolved the issue, change the LogLevel to a more appropriate value. 解决问题后,将LogLevel更改为更合适的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM