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>
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");
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 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);
}
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?