0

With sample codes below,

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);
}

Why is HttpClient returning Internal Server Error (500) on the API controller with parameterized constructor? See this code "roleController.ExecuteRequestAsync()".

Please note that IoC have been configured and working fine.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dennis Laping
  • 682
  • 1
  • 7
  • 18

1 Answers1

1

I finally found the answer here How can I debug a 500 Internal Server Error when calling a WebApi from ajax?

I updated the sample code by adding the Expression parameter in ExecuteRequestAsync method. It turned out that the Expression class expects my controller to have a default constructor defined explicitly. The Expression class throws an ArgumentException in NewExpression New(Type type). Apparently the type should have a constructor that takes no arguments.

So whenever you feel lost with the (500) Internal Server Error, just try the suggested step on the SO link I referenced above. Not the neatest way, but it works. Usually the first exception thrown is the root cause and then you can uncheck the "Break when this exception type is thrown" on the other exceptions because it could throw a lot of exceptions.

Community
  • 1
  • 1
Dennis Laping
  • 682
  • 1
  • 7
  • 18