我有使用异步方法的WebApi控制器Post:
public class WebApiController : ApiController
{
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
try
{
string json = await request.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<TModel>(json);
var newEntity = Mapper.Map<TEntity>(model);
var newEntityVersion = Mapper.Map<TEntityVersion>(model);
var result = await CurrentRepository.AddAsync(newEntity, newEntityVersion);
return CreateResponse(result, "DefaultApiPost");
}
catch (Exception e)
{
Logger.Error("Post in " + ControllerName, e);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
}
}
}
AddAsync方法如下:
public virtual async Task<TEntity> AddAsync(TEntity entity, TEntityVersion version)
{
await DatabaseContext.SaveChangesAsync();
return entity;
}
当我使用HttpClient调用Post方法时,我可以输入AddAsync方法:
client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
但是当我使用WebApi控制器显式调用Post方法时,我无法输入AddAsync方法,只需跳过它:/:
var product = FakeProduct();
var newEntity = Mapper.Map<ProductEntity>(product);
var newEntityVersion = Mapper.Map<ProductVersionEntity>(product);
productRepository.AddAsync(newEntity, newEntityVersion).Returns(Task.FromResult<ProductEntity>(newEntity));
var content = JsonConvert.SerializeObject(Product);
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8888/api/Product/")
{
Content = new StringContent(content),
};
var webApiController = FakeWebApiControllerWithPostRoute();
var result = await webApiController.Post(request);
Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
知道为什么不执行此方法?