C# 如何将AntiForgeryToken与Fetch一起使用?

C# 如何将AntiForgeryToken与Fetch一起使用?,c#,asp.net-core-mvc,fetch,C#,Asp.net Core Mvc,Fetch,我不知道如何使用AntiForgeryToken进行取回调用。对于我在这里找到的AJAX示例: 我可以用同样的方法实现Fetch吗?我找不到任何这样的例子。任何帮助都将不胜感激 我的控制器的方法如下所示: [Route("comments/new")] public ActionResult AddComment(Survey survey) { survey.Time = DateTime.Now; _conte

我不知道如何使用AntiForgeryToken进行取回调用。对于我在这里找到的AJAX示例:

我可以用同样的方法实现Fetch吗?我找不到任何这样的例子。任何帮助都将不胜感激

我的控制器的方法如下所示:

[Route("comments/new")]
        public ActionResult AddComment(Survey survey)
        {
            survey.Time = DateTime.Now;
            _context.Surveys.Add(survey);
            _context.SaveChanges();
            return Content("Added");
        }
和前端:

const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
                    fetch(`/comments/new?${queryParams}`)
                        .then(res => res.json())
                        .then(res => {
                            console.log(res);
                        })
                        .catch(error => {
                            console.error(error);
                        });
我的最终解决方案。 在
Startup.cs
中需要添加:

//config found in some tutorial, sometimes you can find with z X-XSRF-TOKEN, didnt test it
public void ConfigureServices(IServiceCollection services)
{
(...)
services.AddAntiforgery(x => x.HeaderName = "X-CSRF-TOKEN");
services.AddMvc();
}
(...)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
        {
            (...)
            app.Use(next => context =>
            {
                if (context.Request.Path == "/")
                {
                    //send the request token as a JavaScript-readable cookie
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
                }
                return next(context);
            });
            app.UseAuthentication();
            app.UseStaticFiles(); //new configs supposed to be before this line
我的
POST
SurveyController.cs
中:

[HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult AddComment(Survey survey)
        {
            if (survey == null)
            {
                return BadRequest();
            }
            survey.Time = DateTime.Now;
            _context.Surveys.Add(survey);
            _context.SaveChanges();

            return Ok();
        }
在我拥有的
Dialog.JS
文件中,需要创建获取cookie的函数:

//it is similar like here: https://www.w3schools.com/js/js_cookies.asp
function getCookie(name) {
    if (!document.cookie) {
        return null;
    }
    const csrfCookies = document.cookie.split(';')
        .map(c => c.trim())
        .filter(c => c.startsWith(name + '='));
    if (csrfCookies.length === 0) {
        return null;
    }
    return decodeURIComponent(csrfCookies[0].split('=')[1]);
}
接下来,当触发
Fetch
时:

var csrfToken = getCookie("CSRF-TOKEN");
                    //recommended way in documentation
                    var url = new URL("http://localhost:58256/Survey/AddComment"),
                        params = { Name: this.state.surveyState.name, Change: this.state.surveyState.change, Opinion: this.state.surveyState.opinion };
                    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
                    fetch(url,
                        {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                "X-CSRF-TOKEN": csrfToken //sending token with request
                            },
                            contentType: "application/json; charset=utf-8",
                            credentials: 'include'
                        }
                    )
                        .then(res => res.json())
                        .then(res => {
                            console.log(res);
                        })
                        .catch(error => {
                            console.error(error);
                        });