3

我正在尝试使用其 REST API 中可用的 POST 方法将二进制文件(Excel、MS-Word 或图像或任何东西)附加到 ServiceNow 票证。

当我尝试使用 Postman 应用程序执行此操作时它工作正常,但是,当我尝试使用 C# 代码执行此操作时,文件被成功添加但是,在文件的开头和结尾有一些数据由于文件无效不再。如果我使用 Notepad++ 打开附件,我可以看到该文件有如下内容:

--dc5fc6f1-c907-4a26-b410-1d54256954d6
Content-Disposition: form-data; name=Attachment; filename=Download_14Jul20151332195868.xlsx; filename*=utf-8''Download_14Jul20151332195868.xlsx

如果我从文件中删除上述行并再次保存,则可以在 excel 中打开文件。任何其他文件类型都会发生同样的事情。

我正在使用以下 URL 将文件发布到 ServiceNow: https://mycompany.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=1abc60ccdabc1c14215fc082ba9619b0&file_name=SampleExcel3.xlsx

以下是我的代码:

        private static string SendMultiPartRequest(string URL, ExecutionEnvironment executionEnvironment)
        {
            var response = "";
            try
            {
                byte[] file_bytes = File.ReadAllBytes(AttachmentFilePath);
                if (!string.IsNullOrWhiteSpace(AttachmentFilePath))
                {
                    using (var client = CreateNewClient(URL, executionEnvironment))
                    {
                        using (var multipartContent = new MultipartFormDataContent())
                        {
                            multipartContent.Add(new StreamContent(new MemoryStream(file_bytes)), "Attachment", AttachmentFilePath.Substring(AttachmentFilePath.LastIndexOf("\\") + 1));
                            //multipartContent.Headers.Remove("Content-Type");

                            Task responseTask = client.PostAsync(WSIUrl, multipartContent).ContinueWith((Task<HttpResponseMessage> authRes) =>
                            {
                                response = HandleResponse(authRes);
                            });

                            responseTask.Wait();
                        }
                    }
                }
                else
                {
                    response = "{ \"ErrorMessage\" : \"Attachment file not specified.\"}";
                }
            }
            catch (Exception ex)
            {
                response = "{ \"ErrorMessage\" : \"Unspecified error: " + ex.Message + " \"}";
            }
            return response;
        }

我也尝试删除标题,但是当我取消注释此行时它无法附加文件:

  //multipartContent.Headers.Remove("Content-Type");

我无法控制 ServiceNow API 如何使用提交的文件。请建议我如何提交二进制文件以附加到 ServiceNow 票证。

更新: 我仍在尝试各种选择,但仍然没有运气。我试图探索 Postman 如何成功附加文件,并从 Postman 应用程序中找到以下代码。但是,我在这段代码中看不到 Postman 如何在有效负载中添加二进制内容:

var client = new RestClient("https://mycompany.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=1abc60ccdabc1c14215fc082ba9619b0&file_name=Sample.xlsx");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "34584fo4-f91a-414f-8fd0-ff44b0c6b345");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", "Basic c4Ajc2NvcmNoOmVOdBEzOSNSQGspqr==");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
IRestResponse response = client.Execute(request);

但是,当我通过邮递员应用程序发送 POST 请求时,它工作正常:邮递员中使用的 URL 是:POST - https://MyCompany.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=1abc60ccdabc1c14215fc082ba9619b0&file_name =样品.xlsx

在此处输入图像描述

4

1 回答 1

2

我终于使用 RestSharp 完成了这项工作。如果其他人正在寻找解决方案,下面是代码:

private static string SendMultiPartRestClient(string URL, ExecutionEnvironment executionEnvironment)
{
    string response;
    try
    {
        if (!string.IsNullOrWhiteSpace(AttachmentFilePath))
        {
            string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(AttachmentFilePath);
            string FileExtension = Path.GetExtension(AttachmentFilePath);
            string AttachmentFileName = $"{FileNameWithoutExtension}{FileExtension}";

            string AskNowPasswordToBeUsed;
            if (executionEnvironment == ExecutionEnvironment.NonProduction)
                AskNowPasswordToBeUsed = AskNowPasswordEagle;
            else
                AskNowPasswordToBeUsed = AskNowPasswordProduction;

            byte[] byteArray = Encoding.ASCII.GetBytes(AskNowUserName + ":" + AskNowPasswordToBeUsed);
            var Auth = Convert.ToBase64String(byteArray);

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
            
            X509Certificate2 c1 = new X509Certificate2(asknowCertPath, CertPass);

            var client = new RestClient(WSIUrl);
            client.Timeout = -1;
            client.AddDefaultHeader(DP_EXTERNAL_URL, URL);
            client.ClientCertificates = new X509CertificateCollection() { c1 };

            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", $"Basic {Auth}");
            request.AddHeader("Accept", "*/*");
            request.AddHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            request.AddParameter("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                File.ReadAllBytes(AttachmentFilePath),
                ParameterType.RequestBody);

            IRestResponse restResponse = client.Execute(request);

            switch (restResponse.ResponseStatus)
            {
                case ResponseStatus.None:
                    response = "{ \"ErrorMessage\" : \"No response\"}";
                    break;
                case ResponseStatus.Completed:
                    response = restResponse.Content;
                    break;
                case ResponseStatus.Error:
                    response = "{ \"ErrorMessage\" : \"Unspecified error: " + restResponse.ErrorMessage + " \"}";
                    break;
                case ResponseStatus.TimedOut:
                    response = "{ \"ErrorMessage\" : \"Request timed out\"}";
                    break;
                case ResponseStatus.Aborted:
                    response = "{ \"ErrorMessage\" : \"Request aborted\"}";
                    break;
                default:
                    response = "{ \"ErrorMessage\" : \"Unspecified response type.\"}";
                    break;
            }
        }
        else
        {
            response = "{ \"ErrorMessage\" : \"Attachment file not specified.\"}";
        }
    }
    catch (Exception ex)
    {
        response = "{ \"ErrorMessage\" : \"Unspecified error: " + ex.Message + " \"}";
    }
    return response;
}
于 2020-08-04T06:11:38.310 回答