我有兩個.Net核心應用程序,一個Web API和客戶端。使用從客戶端發送郵報:.net Core 2.0 web api 400錯誤使用Validateantiforgerytoken
<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進行通信:
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控制器:
[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錯誤。
我是否缺少啓動配置中的任何其他設置?
它是有道理的,我檢查了博客,不能真正遵循關於Axios的部分。將盡力找到一個循序漸進的例子。謝謝你指點我正確的方向。 – hncl