简体   繁体   English

如何调用异步控制器并返回Task <IHttpActionResult> 直接在C#中

[英]How to call a controller that is async and return Task<IHttpActionResult> directly in C#

I'm trying to get the results of an action from a controller directly without doing an http request 我正在尝试直接从控制器获取操作的结果,而不执行http请求

right now instantiating the controller and calling the method trying to add the results to some item which is in an diferent type 现在实例化控制器并调用该方法以尝试将结果添加到不同类型的某项中

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

It says I can't implicitly convert the type, in my case to a DTO class I have, I'm expecting to get the value of the response (object) just like an HTTP Request but directly and cast it. 它说我无法将类型隐式转换为我拥有的DTO类,我希望像HTTP请求一样直接获取响应(对象)的值,但直接进行转换。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM