2016-11-07 67 views
1
public async Task<HttpResponseMessage> getOne(HttpRequestMessage request, int id) 
{ 

    return CreateResponse(async() => 
    { 
     var category = await _unitOfWork.Categories.GetSingleAsync(id); 
     var categoryVm = Mapper.Map<Category, CategoryViewModel>(category); 

     HttpResponseMessage response = request.CreateResponse<CategoryViewModel>(HttpStatusCode.OK, categoryVm); 

     return response; 
    }); 
} 

基類如何創建方法接受任務lambda表達式異步

protected Task<IHttpActionResult> CreateResponse(Func<IHttpActionResult, Task> function) 
{ 
    IHttpActionResult response = null; 
    try 
    { 
     response = function.Invoke(); 

    } 
} 

回答

1

跨領域閱讀起來關注

你給自己不必要的麻煩。您的示例可以簡化爲:

public async Task<IHttpActionResult> getOne(int id) { 
    var category = await _unitOfWork.Categories.GetSingleAsync(id); 
    var categoryVm = Mapper.Map<Category, CategoryViewModel>(category); 
    return Ok(categoryVm); 
} 

儘量保持控制器精益。

檢查this答案