How to upload a file to SNOW using REST API and C#

Naresh U
Kilo Contributor

Hello SNOW Community,

I am trying to upload a document to an incident record using an ASP.Net C# application. Below is the code. I am receiving 400 Bad Request response. Any clues what I am doing wrong? Your help is much appreciated.

using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://myinstance.service-now.com/api/now/attachment/upload"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");

string authData = string.Format("{0}:{1}", "username", "pwd");
string authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("tableName"), "table_name");
multipartContent.Add(new StringContent("incidentSysid"), "table_sys_id");
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("filePath")), "uploadFile", Path.GetFileName("filePath"));
request.Content = multipartContent;

var response = await httpClient.SendAsync(request);
}
}

Thank you,

Naresh

1 ACCEPTED SOLUTION

Abhishek Pidwa
Kilo Guru

Hey Naresh, 

 

I have done similar stuff in my local environment so I did modify and add the required code in my local visual studio. Basically I am against HTTPClient and would like to use RestSharp.dll to perform all these actions. This is a full-proof working solution . Also 400 Bad request can mean a lot of things and is basically a pain point to figure out what exactly is wrong in your situation. Try this code:

 

find_real_file.png

 

For Authorization it will have a value (same way as you are encrypting currently. make sure that it is a valid username/password in your system.I am sure you just wrote user password to avoid showing to us in the forum) like this in my Web.config:

 

find_real_file.png

 

 

Make sure that the path of the file which you provide is right. Try with a sample file in your desktop and then change it accordingly. 

 

After you run this code, you will see a sample document attached :

 

find_real_file.png

 

 

Happy coding. 

 

 Please mark this as correct answer if this solves your problem. 

View solution in original post

6 REPLIES 6

Sergey Popov
Tera Expert

Here is the working solution using the standard HttpClient. 
Notice, there is a /file endpoint, not /upload one.

 

            using HttpClient client = new();
            client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(_settings.CurrentValue.ServiceNowUsername, _settings.CurrentValue.ServiceNowPassword);

            var url = _settings.CurrentValue.ServiceNowUrl + "/api/now/attachment/file";

            url += "?table_name=" + HttpUtility.UrlEncode(tableName);
            url += "&table_sys_id=" + HttpUtility.UrlEncode(sysId);
            url += "&file_name=" + HttpUtility.UrlEncode(fileName);

            HttpRequestMessage request = new (HttpMethod.Post, url);
            request.Content = new StreamContent(stream);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("binary/octet-stream");

            return await client.SendAsync(request);

 

 

ragoo_prave
Tera Contributor

Hi Abhishek,

  I'm trying to use your code after 5 years but ending up with a error - Bad request - missing table name.
Response Code: BadRequest
Response Body: {"error":{"message":"Missing parameter: table_name","detail":null},"status":"failure"}
Can you please help me to get this working as I'm stuck due to this for almost 2 weeks?
using RestSharp 112.1.0 version

var restClient = new RestClient("https://dev.service-now.com/api/now/v1/attachment/upload");
restClient.AddDefaultHeader("Authorization", $"Basic {credentials}");
restClient.AddDefaultHeader("Content-Type", "multipart/form-data");

 

var request = new RestRequest("", Method.Post);
//request.AddHeader("Authorization", $"Basic {credentials}");
request.AddHeader("Accept", "*/*");
// request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Accept-Encoding", "gzip,deflate,br");
request.AddHeader("Content-Type", "multipart/form-data");
request.AddParameter("table_name", "incident");
request.AddParameter("table_sys_id", recordSysId);
request.AddFile("sample.txt", "C:\\Users\\XXXXX\\Desktop\\sample.txt");
request.AlwaysMultipartFormData = true;

RestResponse response = (RestResponse)restClient.Execute(request);