asp.net-core - Ajax 发布到 ASP .NET 2.2 Razor 页面时出现 404 错误

标签 asp.net-core razor asp.net-core-mvc

我似乎无法让它与最新的 .NET Core 2.2 Razor 一起使用。 我对 URL 进行了硬编码以确保它是正确的。 ajax 脚本在局部 View 中,但我确实测试过将脚本移动到主页,结果相同,结果为 404。

$.ajax({
    type: 'POST',
    url: 'https://localhost:44349/Admin/Catalog/Products/Edit?handler=Filter&id=1',
    success: function (data) {
        alert("success");
    },
    error: function (xhr, textStatus, error) {
        alert(xhr.statusText);
    }
});

这是我的处理程序:

public IActionResult OnPostFilter(int id)
        {
            return new JsonResult("test");
        }

我在 Startup 中禁用了 AntiForgery Token 只是为了确保这不会导致我的问题:

    services.AddMvc().AddRazorPagesOptions(o =>
    {
        o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
    });

最佳答案

404 表示 url 不正确。

Razor 页面在发送 POST 请求时需要设置一个 RequestVerificationToken header :

在您的 View 中添加 @Html.AntiForgeryToken(),然后像这样更改您的 ajax:

$.ajax({
            type: 'POST',
            url: 'https://localhost:44349/Admin/Catalog/Products/Edit?handler=Filter',
            contentType: 'application/x-www-form-urlencoded',
            dataType:'json',
            data: {
                 id: 1                  
            },
            headers:
            {
                "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            success: function (data) {
                alert("success");
            },
            error: function (xhr, textStatus, error) {
                alert(xhr.statusText);
            }
        });

关于asp.net-core - Ajax 发布到 ASP .NET 2.2 Razor 页面时出现 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55486184/

相关文章:

c# - Url.RouteUrl 在 ASP.NET Core 3.0 中为空

angular - 使用基本 href 从不同的子目录提供 angular2

c# - 包含特定字符的 ActionLink 路由值

Razor, MVC4, @html.dropdownlistfor 问题

asp.net-core - 如何在asp.net core 1.0中获取当前的url

asp.net-mvc - 构建面向完整 .net 框架的 VS2017 .net core 应用程序

entity-framework - 使用 F# 配置 EF Core

ajax - 提交Ajax表单后如何用消息更新_Layout.cshtml中的DIV?

c# - 从中间件重写 Asp.net Core url 不起作用

asp.net core mvc 中的 CKEditor 数据绑定(bind)