Как удалить вложение из Jira 4.4 с помощью Http - PullRequest
1 голос
/ 08 марта 2012

Я искал способ удалить вложение из Jira с использованием SOAP Api, но кажется, что это невозможно изначально, и я бы предпочел не реализовывать новый плагин для Jira, как предложено в принятомответьте на этот вопрос или перекомпилируйте существующий плагин для поддержки этого, как указано здесь .

Этот ответ на вышеупомянутый вопрос, кажется, делаетименно то, что я хочу, но, увы, я не могу заставить меня работать.В ответ я получаю сообщение об ошибке, в котором говорится:

Маркер безопасности XSRF отсутствует

JIRA не удалось выполнить это действие из-за отсутствующего токена формы.

Возможно, вы очистили файлы cookie вашего браузера, что могло привести к истечению срока действия вашего текущего токена формы.Новый токен формы был переиздан.

Поскольку я использую Asp.Net MVC C #, я использовал код из ответа, , как , толькоизмененный URL-адрес сервера, а также различные учетные данные (пользователь Jira) и имя пользователя / пароль, переданные в качестве параметров запроса с использованием:

os_username=jirausername&os_password=xxxxxxx

Код, который я сейчас использую, выглядит следующим образом:

public void RemoveAttachment(string issueid, string attachmentid)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                //Compute jira server base url from WS url
                string baseUrl = _service.Url.Substring(0, _service.Url.IndexOf("/rpc/"));

                //Compute complete attachment url
                string attachmenturl = baseUrl + "/secure/DeleteAttachment.jspa?id=" +
                                       issueid + "&deleteAttachmentId=" + attachmentid;

                client.Credentials = new System.Net.NetworkCredential("jirausername", "xxxxxxx");
                string response = client.DownloadString(attachmenturl);
            }
    }

1 Ответ

0 голосов
/ 23 марта 2012

В итоге я использовал метод, который сначала запрашивает форму подтверждения удаления, затем извлекает из формы требуемый токен и, наконец, публикует что-то эквивалентное содержимому формы, чтобы удалить вложение.Код ниже.

public void RemoveAttachment(string issueid, string attachmentid)
{
    //Compute jira server base url from WS url
    string baseUrl = _service.Url.Substring(0, _service.Url.IndexOf("/rpc/"));

    //Compute complete attachment deletion confirm url
    string confirmurl = baseUrl + "/secure/DeleteAttachment!default.jspa?id=" +
                 issueid + "&deleteAttachmentId=" + attachmentid + "&os_username=jirauser&os_password=xxxxxx";

    //Create a cookie container to maintain the xsrf security token cookie.
    CookieContainer jiracontainer = new CookieContainer();

    //Create a get request for the page containing the delete confirmation.
    HttpWebRequest confirmrequest = (HttpWebRequest)WebRequest.Create(confirmurl);
    confirmrequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
    confirmrequest.CookieContainer = jiracontainer;

    //Get the response and the responsestream.
    WebResponse confirmdeleteresponse = confirmrequest.GetResponse();
    Stream ReceiveStream = confirmdeleteresponse.GetResponseStream();

    // Open the stream using a StreamReader for easy access.
    StreamReader confirmreader = new StreamReader(ReceiveStream);
    // Read the content.
    string confirmresponse = confirmreader.ReadToEnd();

    //Create a regex to extract the atl/xsrf token from a hidden field. (Might be nicer to read it from a cookie, which should also be possible).
    Regex atl_token_matcher = new Regex("<input[^>]*id=\"atl_token\"[^>]*value=\"(?<token>\\S+)\"[^>]*>", RegexOptions.Singleline);
    Match token_match = atl_token_matcher.Match(confirmresponse);

    if (token_match.Success)
    {
        //If we found the token get the value.
        string token = token_match.Groups["token"].Value;

        //Compute attachment delete url.
        string deleteurl = baseUrl + "/secure/DeleteAttachment.jspa";

        //Construct form data.
        string postdata = "atl_token=" + HttpContext.Current.Server.UrlEncode(token) + "&id=" + issueid + "&deleteAttachmentId=" + attachmentid + "&Delete=Delete&os_username=jirauser&os_password=xxxxxx";

        //Create a post request for the deletion page.
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(deleteurl);
        request.KeepAlive = false;
        request.CookieContainer = jiracontainer; // Remember to set the cookiecontainer.
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";

        //Turn our request string into a byte stream
        byte[] postBytes = Encoding.ASCII.GetBytes(postdata);

        //Make sure you specify the proper type.
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postBytes.Length;
        Stream requestStream = request.GetRequestStream();

        //Send the post.
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();

        //Get the response.
        WebResponse deleteresponse = request.GetResponse();

        // Open the responsestream using a StreamReader for easy access.
        StreamReader deleteresponsereader = new StreamReader(deleteresponse.GetResponseStream());

        // Read the content.
        string deleteresponsecontent = deleteresponsereader.ReadToEnd();

        // do whatever validation/reporting with the response...
    }
    else
    {
        //We couldn't find the atl_token. Throw an error or something...
    }

}

Редактировать: То же самое работает для удаления комментариев.Замените «attachment» на «comment» и «deleteAttachmentId» на «commentId», и вам будет хорошо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...