【问题标题】:InvalidOperationException: Multiple handlers matched. The following handlers matched route data and had all constraints satisfied:InvalidOperationException:匹配了多个处理程序。以下处理程序匹配路由数据并满足所有约束:
【发布时间】:2018-12-13 17:38:59
【问题描述】:

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

我在 Microsoft Visual Studio 2017 中为 .NET Core 2.1 构建应用程序时收到此错误。这是我认为其中包含错误的视图。它用于主 index.cshtml 剃须刀页面。

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()
    {

    }
}

【问题讨论】:

    标签: c# razor asp.net-core razor-pages


    【解决方案1】:

    Razor 页面使用基于约定的处理程序进行导航。

    当前的 PageModel 有两个 Get 处理程序 Tasks.Task OnGetAsync()Void OnGet(),正如异常中明确说明的那样。

    框架无法确定使用哪一个。

    删除void OnGet,因为它似乎未使用。

    还建议检查 OnPostDeleteAsync 的命名,因为这也可能导致路由问题。

    您可以为任何 HTTP 动词添加处理程序方法。最普遍的 处理程序是:

    • OnGet 初始化页面所需的状态。 OnGet 示例。
    • OnPost 处理表单提交。

    Async 命名后缀是可选的,但通常按约定使用 用于异步函数。

    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");
        }   
    }
    

    参考Introduction to Razor Pages in ASP.NET Core

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多