gpt4 book ai didi

asp.net - ASP.NET Web API 内存测试中的内部服务器错误

转载 作者:行者123 更新时间:2023-12-04 13:24:06 26 4
gpt4 key购买 nike

in-memory test 中测试 ASP.NET Web API Controller 时出现“内部服务器错误”(状态代码 500) .

[TestFixture]
public class ValuesControllerTest
{
private HttpResponseMessage response;

[TestFixtureSetUp]
public void Given()
{
var config = new HttpConfiguration
{
IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
};

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = typeof(ValuesController).Name.Replace("Controller", string.Empty), id = RouteParameter.Optional }
);

//This method will cause internal server error but NOT throw any exceptions
//Remove this call and the test will be green
ScanAssemblies();

var server = new HttpServer(config);
var client = new HttpClient(server);
response = client.GetAsync("http://something/api/values/5").Result;
//Here response has status code 500

}

private void ScanAssemblies()
{
PluginScanner.Scan(".\\", IsApiController);
}

private bool IsApiController(Type type)
{
return typeof (ApiController).IsAssignableFrom(type);
}

[Test]
public void Can_GET_api_values_5()
{
Assert.IsTrue(response.IsSuccessStatusCode);
}
}

public static class PluginScanner
{
public static IEnumerable<Type> Scan(string directoryToScan, Func<Type, bool> filter)
{
var result = new List<Type>();
var dir = new DirectoryInfo(directoryToScan);

if (!dir.Exists) return result;

foreach (var file in dir.EnumerateFiles("*.dll"))
{
result.AddRange(from type in Assembly.LoadFile(file.FullName).GetTypes()
where filter(type)
select type);
}
return result;
}
}

我已将 Visual Studio 配置为在抛出任何 .Net 异常时中断。代码不会因任何异常而停止,我也无法在响应中找到任何异常详细信息。

我应该怎么做才能查看导致“内部服务器错误”的原因?

最佳答案

异常(exception)是在 Response.Content

if (Response != null && Response.IsSuccessStatusCode == false)
{
var result = Response.Content.ReadAsStringAsync().Result;
Console.Out.WriteLine("Http operation unsuccessful");
Console.Out.WriteLine(string.Format("Status: '{0}'", Response.StatusCode));
Console.Out.WriteLine(string.Format("Reason: '{0}'", Response.ReasonPhrase));
Console.Out.WriteLine(result);
}

关于asp.net - ASP.NET Web API 内存测试中的内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710314/

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