c# - 如何在 Web API 的异步方法中返回 Void

标签 c# asp.net-web-api

我正在从存储库调用 Web API(C#) 中的方法。该方法是存储库不返回任何内容。它是虚空的。为什么我应该在我的 API 方法中返回,因为异步方法不能有 Void 返回类型。

这是我在 API 中的异步方法:

    [HttpPost]
    [Route("AddApp")]
    public async Task<?> AddApp([FromBody]Application app)
    {        
        loansRepository.InsertApplication(app);
    }

这是 EntityFrame 工作插入存储库(我可以顺便更改它)

     public void InsertApplication(Application app)
    {

        this.loansContext.Application.Add(app);
    }

抱歉,我对问题进行了更改,我不确定我应该做什么?在任务中

最佳答案

如果你不想返回任何东西,那么返回类型应该是Task

[HttpPost]
[Route("AddApp")]
public async Task AddApp([FromBody]Application app)
{
    // When you mark a method with "async" keyword then:
    // - you should use the "await" keyword as well; otherwise, compiler warning occurs
    // - the real return type will be:
    // -- "void" in case of "Task"
    // -- "T" in case of "Task<T>"
    await loansRepository.InsertApplication(app);
}

public Task InsertApplication(Application app)
{
    this.loansContext.Application.Add(app);

    // Without "async" keyword you should return a Task instance.
    // You can use this below if no Task is created inside this method.
    return Task.FromResult(0);
}

关于c# - 如何在 Web API 的异步方法中返回 Void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37039751/

相关文章:

c# - Recaptcha 和 Windows Phone

c#-4.0 - 在 MVC4 中尝试使用 Async、Task 和 Await 异步的 ValidationAttribute

c# - 如何尝试将字符串转换为 Guid

c# - 不要使用 Type.GetMethods() 返回 ToString、Equals、GetHashCode、GetType

c# - 为什么对于那些喜欢类型安全的人来说 Null 不是类型安全的无关紧要

c# - 字符串格式 : remove the last underscore and the following characters

c# - 如何使 ObservableCollection 中的项目独一无二?

asp.net - 如何从 ApiController 创建 MVC 操作的 url?

c#-4.0 - Web APi 中的每个操作后触发特定方法

c# - 如何解密 Web API 2 JWT token ?