为什么我收到此 Razor 页面 Ajax 调用的 404?

Why do I get a 404 for this Razor Page Ajax call?

我正在 Register 页面中调用一个 Ajax 函数,使用以下客户端代码:

$.ajax({
    type: "GET",
    url: "/Register?handler=GeneratePassword",
    contentType: "application/json",
    dataType: "json",
    success: function (response) {
        $("#genPwd").val(response.Password);
    },
    failure: function (response) {
        alert(response);
    }
});

页面模型中的操作如下所示:

public JsonResult OnGetGeneratePassword()
{
    var pwd = _passwordService.GeneratePassword(_passwordOptions);
    return new JsonResult(new { Ok = true, Password = pwd });
}

根据我读到的有关 Razor 页面 Ajax 调用的内容,这应该有效,那么为什么是 404?

您是否尝试过使用 IActionResult 而不是 JsonResult

public IActionResult OnGetGeneratePassword()
{
    var pwd = _passwordService.GeneratePassword(_passwordOptions);
    return new JsonResult(new { Ok = true, Password = pwd });
}

您还可以尝试删除 ajax url 开头的 / ,如下所示:

$.ajax({
    type: "GET",
    url: "Register?handler=GeneratePassword",