简体   繁体   中英

how to call an async MVC controller method from ajax

I have a controller method that is doing a db lookup for user that is logged in, then it will send a confirmation email, looks like this:

[HttpPost]
public async void ResendConfirmationEmail(string username)
{
    var user = await Usermanager.FindByNameAsync(username);
    try { SendRegistrationEmail(user); }
    catch (Exception e)
    {
        //TODO: LOGGIN EMAIL ERROR
        throw e;
    }
}

I want to call this from a ajax function like this:

 var ResendRegEmail = function (identity) { $.ajax({ type: "POST", url: "/Customer/ResendConfirmationEmail", data: { username: identity }, success: function (data) { $("#ResendModal").modal('show'); $("#msgSuccess").html("Email has been sent succesfully please check your email."); }, error: function (request, textStatus, errorThrown) { $("#ResendModal").modal('show'); $("#msgError").html(textStatus + " " + errorThrown); } }) } 

[AllowAnonymous]
public async void SendRegistrationEmail(JustAskUser user)
{ code here }

if I remove the async the "resendCOnfirmationEmail" function works as expected, but the business requirement is using async to keep the flow of the site as fast as possible. Currently receiving a resource wont load 500 error

but then i get an error from "sendregistrationEmail" - {"An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async=\\"true\\" %>. This exception may also indicate an attempt to call an \\"async void\\" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it."}

I believe your issue to be the line where you call SendRegistrationEmail . Because this method is async you should have an await keyword before the method name.

The error message contains the solution as stated.

... Instead, the asynchronous method should return a Task, and the caller should await it

So your method should be modified like so:

[HttpPost]
public async void ResendConfirmationEmail(string username)
{
    var user = await Usermanager.FindByNameAsync(username);
    try 
    { 
        await SendRegistrationEmail(user); 
    }
    catch (Exception e)
    {
        //TODO: LOGGIN EMAIL ERROR
        throw e;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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