将 razor 页面中 ajax post 的目标从控制器中的 api 更改为同一 razor 页面中的 "code-behind" post 处理程序
Change target of ajax post in razor page from api in controller to "code-behind" post handler in same razor page
我的 index.cshtml 剃须刀页面上有以下 ajax post,效果很好:
create: {
url: "/api/LearningTasks/create",
type: "POST",
dataType: "json"
},
它将 post 发送到我的控制器并且代码接收工作正常。看起来像这样:
[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);
}
我想更改 post 的目标,以便它转到 "code-behind" 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: "",
但均无效。任何帮助弄清楚如何做到这一点将不胜感激。
Razor 页面旨在自动保护免受 cross-site 请求伪造 (CSRF/XSRF) 攻击。
您应该使用 AJAX:
将请求 header 中的 anti-forgery 令牌发送到服务器
使用 @Html.AntiForgeryToken()
显式添加,它将添加一个隐藏的输入类型,名称为 __RequestVerificationToken
.
在请求中发送令牌 header :
$.ajax({
url: '/Index',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
})
.done(function (result) { })
配置防伪服务以查找 X-CSRF-TOKEN header :
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
以下文章供您参考:
我的 index.cshtml 剃须刀页面上有以下 ajax post,效果很好:
create: {
url: "/api/LearningTasks/create",
type: "POST",
dataType: "json"
},
它将 post 发送到我的控制器并且代码接收工作正常。看起来像这样:
[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);
}
我想更改 post 的目标,以便它转到 "code-behind" 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: "",
但均无效。任何帮助弄清楚如何做到这一点将不胜感激。
Razor 页面旨在自动保护免受 cross-site 请求伪造 (CSRF/XSRF) 攻击。
您应该使用 AJAX:
将请求 header 中的 anti-forgery 令牌发送到服务器使用
@Html.AntiForgeryToken()
显式添加,它将添加一个隐藏的输入类型,名称为__RequestVerificationToken
.在请求中发送令牌 header :
$.ajax({ url: '/Index', type: 'POST', beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); }, }) .done(function (result) { })
配置防伪服务以查找 X-CSRF-TOKEN header :
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
以下文章供您参考: