NET Core C#中如何使用HttpClient在标头中添加“ X-XSRF-TOKEN”

时间:2019-08-21 14:23:23

标签: c# asp.net-core asp.net-web-api httpclient

我有多个Cookie可以通过.net中的HttpClient附加到发布请求中,并且还需要在标头中附加“ X-XSRF-TOKEN”。

我通过邮递员提出了要求,并且效果很好。 邮递员的屏幕截图,其中标题如下。 enter image description here

到目前为止,我编写的代码如下。

 public class testController : Controller
    {

        public static Uri baseAddress = new Uri("https://phasma.demisto.works");
        public static Cookie cookie_XSRF_TOKEN = new Cookie("XSRF-TOKEN", "XXXXXXX");
        public static Cookie cookie_inc_term = new Cookie("inc-term", "XXXXXXX");
        public static Cookie cookie_S_Expiration = new Cookie("S-Expiration", "XXXXXXX");
        public static Cookie cookie_S = new Cookie("S", "XXXXXXX");


        public testController(ILogger<testController> logger, IUnitOfWork uow) 
        {
            cookieContainer.Add(baseAddress, cookie_S_Expiration);
            cookieContainer.Add(baseAddress, cookie_S);
            cookieContainer.Add(baseAddress, cookie_XSRF_TOKEN);
            cookieContainer.Add(baseAddress, cookie_inc_term);
        }
        public static CookieContainer cookieContainer = new CookieContainer();
        public static HttpClientHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer };
        public HttpClient client = new HttpClient(handler) { BaseAddress = baseAddress };






        public  async Task<IActionResult> Index()
        {
            string query = @"{some json objects }";
            HttpContent queryContent = new StringContent(query, System.Text.Encoding.UTF8, "application/json");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //ACCEPT header


            client.DefaultRequestHeaders.Add("X-XSRF-TOKEN", "XXXXX");  




            HttpResponseMessage result = await client.PostAsync("/incidents/search", queryContent);
            CookieCollection collection = handler.CookieContainer.GetCookies(baseAddress); // Retrieving a Cookie
            var result2 = JsonConvert.DeserializeObject<object>(result.Content.ReadAsStringAsync().Result);
            return Ok(result2); ;
        }

这是我得到的错误

 {"id":"forbidden","status":403,"title":"Forbidden","detail":"Issue with CSRF code","error":"","encrypted":false,"multires":null}

另一个异常如下

{"id":"bad_request","status":400,"title":"Bad request","detail":"Request body is not well-formed. It must be JSON.","error":"invalid character '\\'' looking for beginning of object key string","encrypted":false,"multires":null}

0 个答案:

没有答案