【发布时间】: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