Basic Authentication Kullanan WebApi Tetikleme | C#

Merhaba, geçenlerde bir firma ile entegrasyonda API için Basic Authentication kullanmam gerekti. Bir de parametre göndermem gerekiyordu.

Şu şekilde kullandım:

    public KeyValuePair<bool, string> IstekGonderBasicAuthentication<T>(string url, T param, string u, string p)
    {
        string authenticationInfo = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(u + ":" + p));
        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.Accept = "application/json";
        httpRequest.Headers["Authorization"] = "Basic " + authenticationInfo;
        httpRequest.ContentType = "application/json";
        string data = JsonConvert.SerializeObject(param);
        using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
        {
            streamWriter.Write(data);
        }
        var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        string sonucStr = "";
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            sonucStr = streamReader.ReadToEnd();
        }
        if (httpResponse.StatusCode == HttpStatusCode.Accepted)
        {
            return new KeyValuePair<bool, string>(true, sonucStr);
        }
        else
        {
            return new KeyValuePair<bool, string>(false, "Status error: (" + httpResponse.StatusCode.ToString() + ")");
        }
    }

Selamlar.

Leave a Reply

Your email address will not be published.