navarq
navarq

Reputation: 1345

InvalidOperationException: Multiple handlers matched. The following handlers matched route data and had all constraints satisfied:

System.Threading.Tasks.Task OnGetAsync(), Void OnGet()

OnGetAsync(), Void OnGet()I receive this error when building an application for .NET Core 2.1 in Microsoft Visual Studio 2017. This is the view I believe has the error within it. It is for the main index.cshtml razor page.

public class IndexModel : PageModel
{
    private readonly AppDbContext _db;

    public IndexModel(AppDbContext db)
    {
        _db = db;
    }

    public IList<Customer> Customers { get; private set; }

    public async Task OnGetAsync()
    {
        Customers = await _db.Customers.AsNoTracking().ToListAsync();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int id)
    {
        var contact = await _db.Customers.FindAsync(id);

        if (contact != null)
        {
            _db.Customers.Remove(contact);
            await _db.SaveChangesAsync();
        }

        return RedirectToPage();
    }

    public void OnGet()
    {

    }
}

Upvotes: 5

Views: 8163

Answers (2)

Eric Eskildsen
Eric Eskildsen

Reputation: 4759

For those using dotnet watch run, try restarting the app (Ctrl+R in the terminal).

I've had this happen after significant code changes. My code had a single matching handler, but .NET thought there was more than one before restart.

Upvotes: 7

Nkosi
Nkosi

Reputation: 247213

Razor pages navigate using convention-based handlers.

The current PageModel has two Get handlers Tasks.Task OnGetAsync(), and Void OnGet() as clearly stated in the exception.

The framework is unable to determine which one to use.

Remove the void OnGet as it appears to be unused.

It would also be advisable to review the naming of OnPostDeleteAsync as this too may cause issue with routing.

You can add handler methods for any HTTP verb. The most common handlers are:

  • OnGet to initialize state needed for the page. OnGet sample.
  • OnPost to handle form submissions.

The Async naming suffix is optional but is often used by convention for asynchronous functions.

public class IndexModel : PageModel {
    private readonly AppDbContext _db;

    public IndexModel(AppDbContext db) {
        _db = db;
    }

    public IList<Customer> Customers { get; private set; }

    public async Task<IActionResult> OnGetAsync() {
        Customers = await _db.Customers.AsNoTracking().ToListAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id) {
        var contact = await _db.Customers.FindAsync(id);

        if (contact != null) {
            _db.Customers.Remove(contact);
            await _db.SaveChangesAsync();
        }    
        return RedirectToPage("/Index");
    }   
}

Reference Introduction to Razor Pages in ASP.NET Core

Upvotes: 11

Related Questions