如何调用异步控制器并直接在C#

时间:2019-02-18 13:40:47

标签: c# .net c#-4.0

我正尝试直接从控制器获取操作结果,而不执行http请求

现在实例化控制器并调用该方法以尝试将结果添加到不同类型的某项中

// other file 
_params.Id = item.Id;
var Presponse = new ProductsController().GetProducts(_params);
item.p = Presponse;

//controller file
public class ProductsController : ApiController
{
    [HttpPost]
    [Route("products")]
    [Compress]
    // controller method signature
    public async Task<IHttpActionResult> GetProducts(TheParams model){ 
       .... some logic ....
       Ok(results) 
    }
}

它说我无法将类型隐式转换为我拥有的DTO类,我希望像HTTP请求一样直接获取响应(对象)的值,然后直接将其强制转换。< / p>

1 个答案:

答案 0 :(得分:0)

// You could use await if your method is async, for simplicity just Result.
  IHttpActionResult actionResult = new ProductsController().GetProducts(_params).Result;

// if your result is a Product Type
  var contentResult = actionResult as OkNegotiatedContentResult<Product>;
  Product product = contentResult.Content;

// Map to your DTO class for example
   ProductDto dto = new ProductDto()
   {
        Id = product.Id,
        Name = product.Name
    };