I am trying to resolve a CSRF issue within my WEB API. I am trying to implement the solution shown here.
我正在尝试在我的WEB API中解决CSRF问题。我正在尝试实现此处显示的解决方案。
From what I can tell, I need to create an @function{ ... } block in my Razor code, which I have done. (Basically the same function from the article)
据我所知,我需要在我的Razor代码中创建一个@function {...}块,我已经完成了。 (基本上与文章中的功能相同)
@functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
I then have an external .js file that tries to call this method via the following:
然后我有一个外部.js文件,试图通过以下方法调用此方法:
$.ajax({
url: url,
type: "POST",
async: false,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken': '@TokenHeaderValue()'
},
error: function (response) {
alert(response.responseText);
},
success: function (response) {
result = response;
}
});
My "TokenHeaderValue()" method never gets called, furthermore I can see in Fiddler that the literal string of "RequestVerificationToken: @TokenHeaderValue()" is what gets passed, instead of the return result of "TokenHeaderValue()".
我的“TokenHeaderValue()”方法永远不会被调用,而且我可以在Fiddler中看到文件字符串“RequestVerificationToken:@TokenHeaderValue()”是传递的内容,而不是“TokenHeaderValue()”的返回结果。
What is going on here? Why won't an actual call to the "TokenHeaderValue()" happen?
这里发生了什么?为什么不会发生对“TokenHeaderValue()”的实际调用?
1 个解决方案
#1
0
If you use a global variable and reference this in your JavaScript it should work.
如果您使用全局变量并在JavaScript中引用它,它应该可以工作。
In your Razor view:
在你的Razor视图中:
<script>window._csrfToken = '@TokenHeaderValue()';</script>
In your JS file:
在你的JS文件中:
$.ajax({
//...
headers: {
'RequestVerificationToken': window._csrfToken
},
//...
});
#1
0
If you use a global variable and reference this in your JavaScript it should work.
如果您使用全局变量并在JavaScript中引用它,它应该可以工作。
In your Razor view:
在你的Razor视图中:
<script>window._csrfToken = '@TokenHeaderValue()';</script>
In your JS file:
在你的JS文件中:
$.ajax({
//...
headers: {
'RequestVerificationToken': window._csrfToken
},
//...
});