Doubt with Webrequest get method passing token

Asked

Viewed 3,016 times

1

I’m trying to read the data of an order, where I send the information via get, Error: Unable to send content with this verb type.

     public string ConsultaPedido(string urlpedido, string NumeroPedido)
        {
            var request = (HttpWebRequest)WebRequest.Create(urlpedido + "/" + NumeroPedido +"/");
            request.ContentType = "application/json";
            request.Method = "GET";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    AuthToken = "8686330657058660259"
                });

                streamWriter.Write(json);
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }
        }

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • What the API you want to query asks as JSON for the query?

  • Leonardo, I added in the image, ask for the order number and token

  • I added an image to the question

2 answers

1


GET method does not contain Body, or you need to send the AuthToken in Header as our colleague said. Try it like this:

public string ConsultaPedido(string urlpedido, string NumeroPedido)
    {
        var request = (HttpWebRequest)WebRequest.Create(urlpedido + "/" + NumeroPedido +"/");
        //request.ContentType = "application/json"; removendo o body
        request.Method = "GET";

        /*using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                AuthToken = "8686330657058660259"
            });

            streamWriter.Write(json);
        }Não há necessidade de adicionar um body, ao invés disso adicione no Header.*/

        request.Headers["AuthToken"] = "8686330657058660259";//Adicionando o AuthToken  no Header da requisição

        var response = (HttpWebResponse)request.GetResponse();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            return streamReader.ReadToEnd();
        }
    }

I removed the Header add line from that question in English

  • Leonardo, it worked, only the html came from the page and not the data, what could have changed? I really appreciate

  • It worked, the path of the api was wrong, I adjusted and now it worked, I will now do the process Deserializeobject, I appreciate the help

  • But out of the way, you used the solution I sent ? just so I knew it was right

  • Yes, it worked, you were right, a doubt, when it is being done Jsonconvert.Deserializeobject it is filling the class data or not yet?

  • It already fills in the data yes, the act of deserializar is to fill in the data msm thing ;)

  • Leonardo, your help was key to unfold things here, now I have one more challenge that would create an API that will receive several items, I know it is ask too much, more independent if you have to do a consulting in doubt, agent combines something: https://answall.com/questions/261017/api-que-received-one-array--of-items

Show 1 more comment

0

You are trying to send a Body in a GET verb where it is not possible. What you can and is most common is you send the token in Header.

Example: inserir a descrição da imagem aqui

Normally I do so, an example method of a test I did:

private List<UserCoupon> GetUserCoupons()
{
    var client = new HttpClient { BaseAddress = new Uri(APIUrl) };

    if (Session["User"] != null)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetToken());

        int userId = GetUserId();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var response = client.GetAsync($"api/coupon/couponlistbyuser?UserId={userId}").Result;

        if (response.IsSuccessStatusCode)
        {
            var ret = response.Content.ReadAsStringAsync();
            var list = JsonConvert.DeserializeObject<List<UserCoupon>>(ret.Result);
            return list;
        }
    }
    return null;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.