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

查看:410
本文介绍了示例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 Page一起使用?

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

未从Ajax调用中调用OnPost。 / p>

The OnPost is not called from the Ajax call.

推荐答案

Razor Pages自动生成并验证防伪令牌以防止 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. 添加防伪令牌通过添加< form> 或直接使用 @ Html.AntiForgeryToken HtmlHelper

  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



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 与我们的请求标头一起发送。

2. Modify your AJAX callback

In the AJAX callback we add additional code to send the XSRF-TOKEN with our request header.

$.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> 来完成此操作:

<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页面都会自动添加一个包含反伪造令牌的隐藏输入字段。已加载:

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天全站免登陆