hncl hncl - 3 years ago 339
C# Question

.net Core 2.0 web api 400 error using Validateantiforgerytoken

I have two .Net Core applications, a Web API and Client. Sending Post from the client using :

<form asp-action="Create" method="post">

Client controller:

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);

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");
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 Controller:

public async Task<IActionResult> PostSecurityQuestion([FromRoute] SecurityQuestion securityQuestion)
if (!ModelState.IsValid)
return BadRequest(ModelState);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSecurityQuestion", new { id = securityQuestion.QuestionId }, securityQuestion);

If I remove
, it works. I also tried to remove
, still I get 400 error.

Am I missing any additional settings in the Startup configurations?

Answer Source

Anti-forgery tokens are used to ensure the form your client submits is the form you issued it---that is, it is not forged.

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.

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download