繁体   English   中英

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

[英]How Return Void in Async Method in 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);
    }

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

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

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

[HttpPost]
[Route("AddApp")]
public void AddApp([FromBody]Application app)
{        
    loansRepository.InsertApplication(app);
}

编译器将警告“返回语句丢失”。 请将代码修改为:

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

   loansRepository.InsertApplication(app)     
 }

暂无
暂无

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

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