使用ASP.NET Core和JQuery启用防伪令牌 [英] Enable Antiforgery Token with ASP.NET Core and JQuery
问题描述
我正在将JQuery与ASP.NET Core 1.0.1一起使用,并且我拥有Ajax调用:
I am using JQuery with ASP.NET Core 1.0.1 and I have the Ajax call:
$("#send-message").on("submit", function (event) {
event.preventDefault();
var $form = $(this);
$.ajax({
url: "api/messages",
data: JSON.stringify($form.serializeToJSON()),
dataType: "json",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
type: "post"
})
.done(function (data, status, xhr) { })
.fail(function (xhr, status, error) { });
对ASP.NET Core的操作:
To the ASP.NET Core action:
[HttpPost("messages")]
public async Task<IActionResult> Post([FromBody]MessagePostApiModelModel model) {
// Send message
}
该表单位于共享视图中,如下所示:
The form is in a shared view and it is the following:
<form id="send-question" method="post">
<textarea name="content"></textarea>
<button class="button" type="submit">Enviar</button>
</form>
提交表单时出现错误:
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery header value "RequestVerificationToken" is not present.
如何通过JQuery Ajax调用启用ASP.NET Core的AntiForgeryToken?
How can I enable ASP.NET Core's AntiForgeryToken with JQuery Ajax calls?
更新
我需要在表单中添加以下asp-controller和asp-action:
I need to add the following asp-controller and asp-action to the form:
<form asp-controller="QuestionApi" asp-action="Post" id="send-question" method="post">
</form>
这将生成防伪令牌.我需要手动将令牌添加到JQuery调用的标头中,如下所示:
This will generate the antiforgery token. And I needed to manually add the token to the headers of the JQuery call as follows:
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"RequestVerificationToken": $form.find("input[name='af_token']").val()
},
有更好的方法吗?
当没有表单并且我只有一个A标记并单击以进行Ajax调用时,如何解决此问题?我可以在页面头上生成一个通用的防伪令牌,以供该页面上的所有ajax调用使用吗?
How do solve this when there is not form and I have only an A tag that when clicked makes the Ajax call? Can I generate a common antiforgery token on my page head to be used by all ajax calls from that page?
推荐答案
mode777的答案只需要添加一小部分即可完成这项工作(我尝试过):
mode777's answer just needs a small addition to make this work (I tried it):
$(document).ajaxSend(function(e, xhr, options) {
if (options.type.toUpperCase() == "POST") {
var token = $form.find("input[name='af_token']").val();
xhr.setRequestHeader("RequestVerificationToken", token);
}
});
实际上,如果您还使用Ajax提交,则根本不需要使用表单. 将其放在您的_layout中:
Actually, if you also submit using Ajax, you don't need to use a form at all. Put this in your _layout:
<span class="AntiForge"> @Html.AntiForgeryToken() </span>
然后您将其添加到javascript中以获取令牌:
Then you pickup the token by adding this to your javascript:
$(document)
.ajaxSend(function (event, jqxhr, settings) {
if (settings.type.toUpperCase() != "POST") return;
jqxhr.setRequestHeader('RequestVerificationToken', $(".AntiForge" + " input").val())
})
@HtmlAntiForgeryToken生成带有反伪造令牌的隐藏输入字段,与使用表单时相同.上面的代码使用类选择器选择范围,然后在其中获取输入字段以收集令牌并将其添加为标头.
The @HtmlAntiForgeryToken generates a hidden input field with the antiforgery token, the same as when using a form. The code above finds it using the class selector to select the span, then gets the input field inside that to collect the token and add it as a header.
这篇关于使用ASP.NET Core和JQuery启用防伪令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!