我不知道这段代码有什么问题,但它仍然没有响应所需的值。
这是我的示例代码:
WebAPI 2:
KOTController.cs
[HttpGet] [Route("testasync")] public IHttpActionResult TestAsync() { try { return Ok(_iKOTManager.TestAsync()); } catch (Exception ex) { logger.Error(ex); return null; } }接口
IKOTManager.cs
Task<int> TestAsync();KOTManager.cs
public async Task<int> TestAsync() { return await Task.Run<int>(() => { return 999 + 23; }); }当我向此API发送请求时,它返回的内容不是数字
<TaskOfint xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System.Threading.Tasks"/>
任何建议都会非常有用。 谢谢。
I don't know whats wrong with this code, but still it doesn't respond the needed value.
Here is my sample code:
WebAPI 2:
KOTController.cs
[HttpGet] [Route("testasync")] public IHttpActionResult TestAsync() { try { return Ok(_iKOTManager.TestAsync()); } catch (Exception ex) { logger.Error(ex); return null; } }Interface
IKOTManager.cs
Task<int> TestAsync();KOTManager.cs
public async Task<int> TestAsync() { return await Task.Run<int>(() => { return 999 + 23; }); }When I send a request to this API, it returns something like this not the number
<TaskOfint xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System.Threading.Tasks"/>
Any advice would be really helpful. Thank you.
最满意答案
您得到该响应是因为您返回任务而不是实际执行它。 框架只是序列化任务对象并返回它。
重构动作以返回Task ,然后await接口上的方法
[HttpGet] [Route("testasync")] public async Task<IHttpActionResult> TestAsync() { try { return Ok(await _iKOTManager.TestAsync()); } catch (Exception ex) { logger.Error(ex); return InternalServerError(); } }参考: Async / Await - 异步编程的最佳实践
此外,在异常的情况下,您应该返回适当的结果而不是null 。 这应该最终被重构,因为控制器内的处理错误被认为是一个跨领域的问题 。 控制器应尽可能精益。
[HttpGet] [Route("testasync")] public async Task<IHttpActionResult> TestAsync() { return Ok(await _iKOTManager.TestAsync()); }You get that response because you are return the Task and not actually executing it. The framework is just serializing the task object and returning that.
Refactor the action to return Task and then await the method on interface
[HttpGet] [Route("testasync")] public async Task<IHttpActionResult> TestAsync() { try { return Ok(await _iKOTManager.TestAsync()); } catch (Exception ex) { logger.Error(ex); return InternalServerError(); } }Reference: Async/Await - Best Practices in Asynchronous Programming
Additionally, in the case of the exception you should return an appropriate result instead of null. This should eventually be refactored out as handling errors within the controller is considered a cross-cutting concern. Controllers should as lean as possible.
[HttpGet] [Route("testasync")] public async Task<IHttpActionResult> TestAsync() { return Ok(await _iKOTManager.TestAsync()); }更多推荐
发布评论