使用ValidateAntiforgerytoken的.net Core 2.0 Web API 400错误 [英] .net Core 2.0 web api 400 error using Validateantiforgerytoken
问题描述
我有两个.Net Core应用程序,一个Web API和一个Client.使用以下命令从客户端发送帖子:
I have two .Net Core applications, a Web API and Client. Sending Post from the client using :
<form asp-action="Create" method="post">
@Html.AntiForgeryToken()
.....
</form>
客户端控制器:
public async Task<IActionResult> Create([Bind("QuestionId,TheQuestion")] SecurityQuestion securityQuestion)
{
_session.SetString(SessionsKeys.Directory, "/SecurityQuestions");
if (ModelState.IsValid)
{
var data = await _theService.PostWebApi(securityQuestion);
if (data.Item3 == "True")
{
return RedirectToAction(nameof(Index));
}
return View(data.Item1);
}
return View(securityQuestion);
}
与Web API通信的方法:
Method to communicate with the Web API:
public async Task<(object, string, string)> PostWebApi(TObject model)
{
var dir = _session.GetString(SessionsKeys.Directory);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_webApiData.WebApiitems.Url);
MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
string stringData = JsonConvert.SerializeObject(model);
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(dir + "/", contentData).Result;
var msg = await response.Content.ReadAsStringAsync();
var theresponse = response.IsSuccessStatusCode.ToString();
return (model,msg,theresponse);
}
}
Web API控制器:
Web API Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> PostSecurityQuestion([FromRoute] SecurityQuestion securityQuestion)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.SecurityQuestion.Add(securityQuestion);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSecurityQuestion", new { id = securityQuestion.QuestionId }, securityQuestion);
}
如果我删除了 [ValidateAntiForgeryToken]
,它会起作用.我还尝试删除了 [Form]
,但仍然出现400错误.
If I remove [ValidateAntiForgeryToken]
, it works. I also tried to remove [Form]
, still I get 400 error.
我是否缺少启动配置中的其他任何设置?
Am I missing any additional settings in the Startup configurations?
推荐答案
防伪令牌用于确保客户提交的表单与您签发的表单相同-即,它不是伪造的.
Anti-forgery tokens are used to ensure the form your client submits is the form you issued it---that is, it is not forged.
在您的情况下,您的客户端应用正在通过 @ Html.AntiForgeryToken()
生成自己的防伪令牌.但是,它不会传递给您创建的用于与Web API对话的 HttpClient
.但是,即使您设法将该防伪令牌传递到Web API,由于它不是由Web API发行的,也很可能会被拒绝.
In your case, your client app is generating its own anti-forgery token via the @Html.AntiForgeryToken()
. But then, it does not get passed to the HttpClient
you create to talk to your Web API. But even if you manage to pass that anti-forgery token to your Web API, it will likely be rejected since it was not issued by the Web API.
您应该更改Web API,以允许客户端获取令牌.这是斯科特·艾伦(Scott Allen)的博客,介绍如何做到这一点:
You should change your Web API to allow your client to get a token. Here is a blog by Scott Allen on how you can do that: