Alma
Alma

Reputation: 4390

How Return Void in Async Method in Web API

I am calling a method in Web API(C#) from repository. The method is repository is not returning anything. It is Void. whay should I return in my API method as a async method cannot have a Void return type.

This is my Async method in API:

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

and this is EntityFrame work Insert in repository(I can cot change this by the way)

     public void InsertApplication(Application app)
    {

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

Sorry I made changes to the question, I am not sure what should I have for ? in the Task

Upvotes: 9

Views: 14355

Answers (3)

suulisin
suulisin

Reputation: 1434

The compiler will warn "Return statement missing". Please modify the code to:

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

   loansRepository.InsertApplication(app)     
 }

Upvotes: -5

Stephen Cleary
Stephen Cleary

Reputation: 456417

Since you "cannot" change the Entity Framework repository, you shouldn't make your action method asynchronous, and you should just return void:

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

Upvotes: 8

Gabor
Gabor

Reputation: 3246

If you do not want to return anything then the return type should be 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);
}

Upvotes: 14

Related Questions