在C#

时间:2019-08-23 10:54:53

标签: c# .net api .net-core dotnet-httpclient

通过邮递员的请求工作正常。而在C#中,给我例外 我从chrome浏览器调用详细信息中获得的cookie和标头值。

  

禁止”,“状态”:403

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

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

由于此行而导致的错误。

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

json对象中的错误

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

0 个答案:

没有答案