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

时间:2016-05-04 23:23:45

标签: c# asp.net-web-api

我从存储库调用Web API(C#)中的方法。该方法是存储库没有返回任何东西。这是虚空。我应该在API方法中返回,因为async方法不能有Void返回类型。

这是我在API中的Async方法:

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

这是EntityFrame工作在存储库中插入(顺便说一下我可以改变这个)

     public void InsertApplication(Application app)
    {

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

抱歉,我对这个问题做了修改,我不知道该怎么办?在任务

3 个答案:

答案 0 :(得分:13)

如果您不想返回任何内容,则返回类型应为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);
}

答案 1 :(得分:8)

由于您“无法”更改实体框架存储库,因此不应使您的操作方法异步,您应该只返回update

void

答案 2 :(得分:-5)

编译器将警告&#34;返回语句丢失&#34;。请将代码修改为:

 [HttpPost]
 [Route("AddApp")]
 public void AddApp([FromBody]Application app)
 {  
     //add configureAwait(false) as it would give better performance.

   loansRepository.InsertApplication(app)     
 }