【问题标题】:HttpClient is returning Internal Server Error (500) on API controller with parameterized constructorHttpClient 使用参数化构造函数在 API 控制器上返回内部服务器错误 (500)
【发布时间】:2015-08-11 15:29:09
【问题描述】:

下面有示例代码,

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 已配置好并且工作正常。

【问题讨论】:

  • 有人吗?有高手吗? TIA。

标签: asp.net asp.net-web-api asp.net-web-api2 dotnet-httpclient asp.net-web-api-routing


【解决方案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 链接上的建议步骤即可。不是最整洁的方式,但它有效。通常抛出的第一个异常是根本原因,然后您可以取消选中其他异常上的“抛出此异常类型时中断”,因为它可能会抛出很多异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-25
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2020-10-13
    • 2018-09-30
    相关资源
    最近更新 更多