【问题标题】:Change target of ajax post in razor page from api in controller to "code-behind" post handler in same razor page将剃须刀页面中 ajax 帖子的目标从控制器中的 api 更改为同一剃须刀页面中的“代码隐藏”帖子处理程序
【发布时间】:2020-06-03 22:30:27
【问题描述】:

我的 index.cshtml 剃须刀页面上有以下 ajax 帖子,效果很好:

create: {
            url: "/api/LearningTasks/create",
            type: "POST",
            dataType: "json"
        },

它将帖子发送到我的控制器,并且代码接收工作正常。它看起来像这样:

[HttpPost]
    [Route("api/LearningTasks/create")]
    public async Task<ActionResult<LearningTask>> CreateLearningTask(LearningTask learningTask)
    {
        _context.LearningTasks.Add(learningTask);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetLearningTask", new { id = learningTask.Id }, learningTask);
    }

我想更改帖子的目标,使其转到“代码隐藏”index.cshtml.cs。我想收到它的方法是这样的:

 public async Task<IActionResult> OnPostAsync()
    {
        // This is where I want to have the send the data for the create operation instead of to /api/LearningTasks/create
        _context.LearningTasks.Add(LearningTask);
        await _context.SaveChangesAsync();

        return null;  
    }

我已尝试删除行 url: "/api/LearningTasks/create", 并将其设置为 url: "", 但均无效。任何帮助弄清楚如何做到这一点将不胜感激。

【问题讨论】:

标签: jquery asp.net-core razor-pages


【解决方案1】:

Razor 页面旨在自动防止跨站点请求伪造 (CSRF/XSRF) 攻击。

您应该使用 AJAX 将请求标头中的防伪令牌发送到服务器:

  1. 使用@Html.AntiForgeryToken()显式添加,它将添加一个隐藏的输入类型,名称为__RequestVerificationToken

  2. 在请求头中发送令牌:

    $.ajax({
        url: '/Index',
        type: 'POST',
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },   
    })
    .done(function (result) { })
    
  3. 配置防伪服务以查找 X-CSRF-TOKEN 标头:

    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    

以下文章供您参考:

Handle Ajax Requests in ASP.NET Core Razor Pages

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2020-11-11
    相关资源
    最近更新 更多