2017-10-01 45 views
1

我有兩個.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錯誤。

我是否缺少啓動配置中的任何其他設置?

回答

0

防僞標記是用來確保您的客戶端提交的是你發出它的形式形式---也就是說,它不是僞造的。

對於您的情況,您的客戶端應用程序正在通過@Html.AntiForgeryToken()生成自己的防僞標記。但是,它不會傳遞到您創建的HttpClient以與Web API交談。但即使您設法將該防僞標記傳遞給您的Web API,它也可能會被拒絕,因爲它不是由Web API發佈的。

您應該更改您的Web API以允許您的客戶端獲得令牌。這裏是你如何能做到這一點了博客斯科特·艾倫:

+0

它是有道理的,我檢查了博客,不能真正遵循關於Axios的部分。將盡力找到一個循序漸進的例子。謝謝你指點我正確的方向。 – hncl

0

Startup.cs文件中ConfigureServices()方法添加以下服務

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); 
+0

謝謝你,我沒有添加它;不幸的是沒有工作 – hncl