C # пост с использованием токена xcsrf с использованием HttpWebRequest - PullRequest
0 голосов
/ 19 июня 2019

C # публикация с использованием токена xcsrf --- Я пытаюсь вызвать метод "Create" вызова API POST, но для этого мне нужно передать CSRFToken (получение значения csrfToken из результата API входа в систему)

Я использую HttpWebRequest этот объект для вызова API

Код:

    uri = "http://domain/services/create?  
    public string HttpUploadFile(string uri, string sourceFilePath, string customerName, string jobNumber, string productType)
    {
        HttpWebRequest request1 = (HttpWebRequest)(WebRequest.Create("http://domain/services/login?username=userID&password=pwd"));
        request1.Method = "POST";
        request1.KeepAlive = true;
        request1.Credentials = new NetworkCredential(userID, pwd);
        string token = "";

        var requestStream2 = request1.GetResponse();

        using (System.IO.Stream responseStream1 = requestStream2.GetResponseStream())
        {

            using (System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream1))
            {
                _responseText = responseReader.ReadToEnd();
                var hh = JsonConvert.DeserializeObject<Dictionary<string, string>>(_responseText);
                token = hh["csrfToken"].ToString();
                System.Diagnostics.Debug.Write(_responseText);

            }
        }
        requestStream2.Close();

        string ElvisIdOfUploadedPdf = "";
        FileInfo fn = new FileInfo(sourceFilePath);
        string filePath = fn.FullName;
        string fileParameterName = "Filedata";
        string contentType = "";
        Dictionary<string, string> otherParameters = new Dictionary<string, string>();

        string metaData = customerName + ", " + jobNumber + ", " + productType;
        otherParameters.Add("filename", fn.Name);
        otherParameters.Add("folderPath", "/" + MainElvisFolder + "/" + productType);
        otherParameters.Add("tags", metaData);

        string boundary = ("---------------------------" + DateTime.Now.Ticks.ToString("x"));
        string newLine = System.Environment.NewLine;
        byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes((newLine + ("--" + (boundary + newLine))));

        HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(uri));
        //request.Credentials = System.Net.CredentialCache.DefaultCredentials;
        request.Credentials = new NetworkCredential(userID, pwd);
        request.ContentType = ("multipart/form-data; boundary=" + boundary);
        request.Headers["x-csrf-token"] = token;
        request.Method = "POST";
        request.KeepAlive = false;

        var requestStream = request.GetRequestStream();
        string formDataTemplate = "Content-Disposition: form-data; name=\"{0}\"{1}{1}{2}";
        foreach (string key in otherParameters.Keys)
        {
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            string formItem = string.Format(formDataTemplate, key, newLine, otherParameters[key]);
            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);
        }

        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}Content-Type:{3}{2}{2}";
        string header = string.Format(headerTemplate, fileParameterName, filePath, newLine, contentType);
        byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
        requestStream.Write(headerBytes, 0, headerBytes.Length);

        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        Int32 bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        while ((bytesRead > 0))
        {
            requestStream.Write(buffer, 0, bytesRead);
            bytesRead = fileStream.Read(buffer, 0, buffer.Length);
        }
        byte[] trailer = System.Text.Encoding.ASCII.GetBytes(newLine + "--" + boundary + "--" + newLine);
        requestStream.Write(trailer, 0, trailer.Length);
       System.Net.WebResponse response = null;

        try
        {

           response = request.GetResponse();

            using (System.IO.Stream responseStream = response.GetResponseStream())
            {

                using (System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream))
                {
                    _responseText = responseReader.ReadToEnd();
                    System.Diagnostics.Debug.Write(_responseText);
                    ElvisIdOfUploadedPdf = _responseText.Substring(7, 22);
                }
            }
        }
        catch (System.Net.WebException exception)
        {
            response = exception.Response;
            if ((response != null))
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    _responseText = reader.ReadToEnd();
                    System.Diagnostics.Debug.Write(_responseText);
                }
                response.Close();
            }
        }
        finally
        {
            request = null;
        }
        return ElvisIdOfUploadedPdf;

    }

ожидаемый результат = _responseText равен json результат Фактический результат = не авторизован / не вошел в систему

...