这个想法是,有两个URL,一个将在get之后生成一个x-csrf-token,另一个将使用该标记作为post。 因此,令牌生成,但post方法返回403禁止 - csrf令牌验证失败。 我使用PostMan工具获取数据,但代码失败,我的猜测是令牌一旦生成就会到期,而在邮递员中它不会。
string Token = "";
string URL = "someurl";
string URL1 = "someurl.method()";
// GET
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Credentials = new NetworkCredential("username", "password");
request.ContentType = "application/json";
request.Method = "GET";
request.Headers["X-CSRF-Token"] = "Fetch";
HttpWebResponse responseH = (HttpWebResponse)request.GetResponse();
Token = responseH.Headers["x-csrf-token"];
// POST
string result = "";
using (var client = new WebClient())
{
string json = "{\"HEAD_HEAD\":[{\"VTWEG\":\"10\",\"KUNAG\":\"1000002\",\"KUNRG\":\"1000002\",\"KUNWE\":\"1000002\",\"KONDM\":\"1A\",\"DATAB\":\"04/18/2017\",\"VSBED\":\"71\",\"HEAD_ITEM\":[{\"Price\":\" \"},{\"Price\":\" \"}]},{\"VTWEG\":\"10\",\"KUNAG\":\"1000000\",\"KUNRG\":\" \",\"KUNWE\":\"1000000\",\"KONDM\":\"B9\",\"DATAB\":\"04/18/2017\",\"VSBED\":\"11\",\"HEAD_ITEM\":[{\"Price\":\" \"},{\"Price\":\" \"}]},{\"VTWEG\":\"10\",\"KUNAG\":\"1000000\",\"KUNRG\":\" \",\"KUNWE\":\"6000004\",\"KONDM\":\"2G\",\"DATAB\":\"04/18/2017\",\"VSBED\":\" \",\"HEAD_ITEM\":[{\"Price\":\" \"},{\"Price\":\" \"}]}]}";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers["X-CSRF-Token"] = Token;
client.Headers[HttpRequestHeader.Accept] = "application/json";
string userName = "username";
string passWord = "password";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
result = client.UploadString(URL1, "POST", json);
}