示例 AJAX 回调到 ASP.NET Core Razor 页面 [英] Example AJAX call back to an ASP.NET Core Razor Page

查看:36
本文介绍了示例 AJAX 回调到 ASP.NET Core Razor 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在一个页面上有多个处理程序的例子以及相关的命名约定(即 OnPostXXX)和asp-post-hanlder"标签助手.但是我如何从 AJAX 调用中调用这些方法之一.

I've found examples of have multiple handlers on a page and the associated naming convention (ie OnPostXXX) and 'asp-post-hanlder' tag helper. But how can I call one of these methods from an AJAX call.

我有一个带有典型 MVC 视图和控制器的旧示例,但它如何与 Razor 页面配合使用?

I have an older example with a typical MVC view and controller but how does this work with a Razor Page?

例如,如果我使用基本应用程序并将 About.cshtml 页面修改为以下内容:

For example if I take the base application and modify the About.cshtml page to the following:

@page
@model AboutModel
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>

    <input type="button" value="Ajax test" class="btn btn-default" onclick="ajaxTest();"  />

@section Scripts {
<script type="text/javascript">
    function ajaxTest() {
        console.log("Entered method");
        $.ajax({
            type: "POST",
            url: '/About', // <-- Where should this point?
            contentType: "application/json; charset=utf-8",
            dataType: "json",
        error: function (xhr, status, errorThrown) {
            var err = "Status: " + status + " " + errorThrown;
            console.log(err);
        }
        }).done(function (data) {
            console.log(data.result);
        })
    }
</script>
}

在模型页面 About.cshtml.cs

And on the model page About.cshtml.cs

public class AboutModel : PageModel
{
    public string Message { get; set; }

    public void OnGet()
    {
        Message = "Your application description page.";
    }

    public IActionResult OnPost() {
        //throw new Exception("stop");
        return new JsonResult("");
    }
}

OnPost 不是从 Ajax 调用中调用的.

The OnPost is not called from the Ajax call.

推荐答案

Razor Pages 自动生成并验证 Antiforgery 令牌以防止 CSRF 攻击.由于您没有在 AJAX 回调中发送任何令牌,因此请求失败.

Razor Pages automatically generates and validates Antiforgery tokens to prevent CSRF attacks. Since you aren't sending any token within your AJAX callback, the request fails.

要解决此问题,您必须:

To solve this problem you will have to:

  1. 注册防伪服务
  2. 将令牌添加到您的请求中
  3. 通过添加
    或直接使用 @Html.AntiForgeryToken HtmlHelper
  4. 将防伪令牌添加到您的页面
  1. Register the Antiforgery-Service
  2. Add the token to your request
  3. Add the antiforgery token to your page either by adding a <form> or by directly using the @Html.AntiForgeryToken HtmlHelper

1.在您的 Startup.cs

中注册 Antiforgery-Service

1. Register the Antiforgery-Service in your Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddRazorPages();
  services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}

2.修改你的 AJAX 回调

在 AJAX 回调中,我们添加了额外的代码来发送带有请求标头的 XSRF-TOKEN.

$.ajax({
    type: "POST",
    url: '/?handler=YOUR_CUSTOM_HANDLER', // Replace YOUR_CUSTOM_HANDLER with your handler.
    contentType: "application/json; charset=utf-8",

    beforeSend: function (xhr) {
      xhr.setRequestHeader("XSRF-TOKEN",
        $('input:hidden[name="__RequestVerificationToken"]').val());
    },

    dataType: "json"
}).done(function (data) {
  console.log(data.result);
})

3.将防伪令牌添加到您的页面

你可以通过添加一个来实现:

<form method="post">
    <input type="button" value="Ajax test" class="btn btn-default" onclick="ajaxTest();" />
</form>

或使用@Html.AntiForgeryToken:

@Html.AntiForgeryToken()
<input type="button" value="Ajax test" class="btn btn-default" onclick="ajaxTest();" />

在这两种情况下,Razor Pages 都会在页面加载后自动添加一个包含防伪标记的隐藏输入字段:

In both cases Razor Pages will automatically add a hidden input field which contains the antiforgery token once the page is loaded:

<input name="__RequestVerificationToken" type="hidden" value="THE_TOKEN_VALUE" />

这篇关于示例 AJAX 回调到 ASP.NET Core Razor 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆