Tips for invoking an async MVC controller function using ajax

Within my controller method, I am performing a database lookup for the logged-in user and then sending a confirmation email. Here is the code snippet:

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

I intend to trigger this function using an AJAX request like so:

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 successfully. 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' keyword, the `resendConfirmationEmail` function works fine. However, it is required to use 'async' to maintain site speed. Currently receiving a resource won't load 500 error.

There is an issue in the `sendRegistrationEmail` function - {"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."}

Answer №1

The issue seems to be with the SendRegistrationEmail method call in your code. Since this method is asynchronous, you need to include the await keyword before calling it.

The solution can actually be found within the error message itself:

... Instead, make sure the asynchronous method returns a Task and the caller awaits it.

To correct this, update your method as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Discover the secrets of flying to customized coordinates stored in variables using Leaflet.js

I'm currently working on a fire location tracking website and I'm facing an issue with leaflet.js. As a newcomer to Leaflet, any assistance would be greatly appreciated! I have a script that successfully retrieves the id of a specific row from a ...

What is the best method to verify the presence of jQuery on a webpage using Python/Selenium WebDriver?

Our in-house automated testing framework is built using Selenium Webdriver in Python, with a mapping system linking object names to identifiers on webpages. However, we are encountering issues due to not waiting long enough for AJAX calls to complete, caus ...

Transforming JSON data into a visual flowchart using VUE.js

In the project I am currently working on, I am faced with the challenge of importing a JSON file (exported from a flowchart drawing project) and converting its data into an actual flowchart. Unfortunately, I have not been able to find any leads on how to c ...

Update the class name by utilizing template literals

I'm currently in the process of mastering template literals as I have a project where I need to utilize them. However, I seem to be encountering an issue that I can't quite figure out. Here is the code that is currently working: const classes = ...

Utilizing Axios recursion to paginate through an API using a cursor-based approach

Is there a way to paginate an API with a cursor using axios? I am looking to repeatedly call this function until response.data.length < 1 and return the complete array containing all items in the collection once the process is complete. Additionally, I ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Step-by-step guide on mocking a method within a method using JEST

Currently, I am facing a challenge in unit testing a method named search. This method consists of three additional methods - buildSearchParameter, isUnknownFields, and readAll. I am looking to mock these methods but I am uncertain about the process. Can ...

What are the benefits of using batch/atomic operations with Selenium RemoteWebDriver?

When examining the source code of the RemoteWebDriver, I noticed that every operation, such as retrieving text from a newly acquired WebElement, involves sending a separate command to the browser. This raises concerns for me, especially in a highly dynamic ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

Adjust the size of an image with jquery without relying on server-side scripts

I am currently developing an application for Samsung Tizen TV that displays images from live URLs. On one screen, there are approximately 150 images, each with a size of around 1 MB and a resolution of 1920 by 1080. Navigating between these items has bec ...

establishing a predetermined dimension using css and integrating it into javascript

I'm a beginner in CSS and JavaScript and I've been searching through various sources for an answer to my question without any luck. My goal is to pre-set the sizes of all sections using CSS and then utilize these sections in JavaScript. However, ...

The function Router.replace within Next Js is not recognized

When attempting to use Router.replace() for replacement, I encounter the error message: TypeError: next_router__WEBPACK_IMPORTED_MODULE_6__.Router.replace is not a function https://i.sstatic.net/Ldmca.png I have attempted to do it in this way: import { ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Tips for adjusting the default selection in a second dropdown menu

I have a dilemma with my two dropdown lists, "optionone" and "optiontwo". I am trying to alter the default selected value from "option value=3>3" to option value=3 selected>3 when the user selects 2 from the first dropdown list ("optionone"). <sc ...

What is the equivalent of {...props} in React for destructuring props in Vue?

When working in React, I can destructure props with ease: function MyComponent() { const myProp = { cx: '50%', cy: '50%', r: '45%', 'stroke-width': '10%' } return ( <svg> ...

Organizing Angular project folders with the help of Node.js and Jade

I've been exploring different folder structures to ensure scalability as my project grows. While I found some useful resources, such as this one, I'm still struggling with how to actually implement these suggestions. Currently, I've adopted ...

Error 404: Postgres and NodeJs API not found (Possible duplicate)

I am new to developing with Node.js and currently working on creating APIs using node, express, and a Postgres database. const {Pool} = require('pg'); //const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/tu ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...