使用以下示例代码,
public class RolesController : ApiController
{
private readonly IRoleService _roleService;
public RolesController(IRoleService roleService)
{
_roleService = roleService;
}
public async Task<IHttpActionResult> Get()
{
return Ok(await Task.FromResult(new[] { "value1", "value2" }));
}
}
public static class TestExtensions
{
public static async Task<HttpResponseMessage> ExecuteRequestAsync<C, A>(this C controller, Expression<Func<C, A>> methodExpressionCall)
{
var methodCall = methodExpressionCall.Body as MethodCallExpression;
var routeAttributes = methodCall.Method.GetCustomAttributes(typeof(RouteAttribute), true);
var routeName = string.Empty;
if (routeAttributes.Count() == 0 || string.IsNullOrEmpty(((RouteAttribute)routeAttributes[0]).Name))
routeName = methodCall.Method.Name.ToLower();
else
routeName = ((RouteAttribute)routeAttributes[0]).Name;
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
using (var client = new HttpClient(new HttpServer(config)))
{
return await client.GetAsync("http://localhost/api/roles/" + routeName);
}
}
}
[Fact]
public void OnCreate_ReturnTrue_IfInputDataAreValid()
{
var roleController = new RolesController(new RoleService());
//Act
var response = roleController.ExecuteRequestAsync(c => c.Get());
//Assert
Assert.Equal(HttpStatusCode.OK, response.Result.StatusCode);
}
为什么HttpClient在API控制器上使用参数化构造函数返回内部服务器错误(500)?请参阅此代码“roleController.ExecuteRequestAsync()”。
请注意IoC已经配置好并且工作正常。
答案 0 :(得分:1)
我终于找到了答案How can I debug a 500 Internal Server Error when calling a WebApi from ajax?
我通过在 ExecuteRequestAsync 方法中添加 Expression 参数来更新示例代码。事实证明,Expression类要求我的控制器显式定义默认构造函数。 Expression类在NewExpression New(Type type)中抛出ArgumentException。显然,类型应该有一个不带参数的构造函数。
因此,每当您感到迷失(500)内部服务器错误时,只需尝试上面引用的SO链接上的建议步骤。不是最好的方式,但它的工作原理。通常抛出的第一个异常是根本原因,然后您可以取消选中“在抛出此异常类型时中断”,因为它可能会引发很多异常。