Azure DevOps REST API - c#

I have read the Azure DevOPS REST API documentation and tried to implement it to my Web Application multiple times but to no avail. I have no experience using REST API's and I would appreciate if someone could guide me into the right direction.
I am trying to create a POST Request for Azure DevOps Repositories and wish to create a new repository through the API method. I have read the documentation on this, but I have no idea how to implement this in my own project. I understand how I need to create a connection to the API, but no idea how and where I write the Request Body for this method. I would like to know how I specify the name of the new repository. I'm actually very clueless and have no idea how to use the REST API in general.
I am using Visual Studio with .NET Core 3.0 and plan to use this with React.js
Here's the code I'm working with so far, and I have no idea where to go from here:
public class AzureDevOps {
public static async void GetRepositories()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/git/repositories?api-version=5.1"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
I would appreciate any clarification on this matter, as well as some examples on how to use the REST API. Thanks in advance!

You should use POST method to create a repository. Check the API here:
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/create?view=azure-devops-rest-5.1
The code should look like:
var PAT = "xxxxx";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1");
requestMessage.Content = new StringContent("{\"name\": \"RepositoryName\",\"project\": {\"id\": \"xxxxxxx\"}}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
}
}
Update:
var PAT = "xxxxx";
var body = new
{
name = "RepositoryName",
project = new
{
id = "xxxxxxx"
}
};
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1");
requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
}
}

Related

ASP.NET Web API post to an external api

I would like to ask if it is possible for a created ASP.NET Web API (written in C#) to post to an external API?
If it is possible, please share sample code that can post to an url with adding headers and receive a callback from the external API.
A simple way to make HTTP-Request out of a .NET-Application is the System.Net.Http.HttpClient (MSDN). An example usage would look something like this:
// Should be a static readonly field/property, wich is only instanciated once
var client = new HttpClient();
var requestData = new Dictionary<string, string>
{
{ "field1", "Some data of the field" },
{ "field2", "Even more data" }
};
var request = new HttpRequestMessage() {
RequestUri = new Uri("https://domain.top/route"),
Method = HttpMethod.Post,
Content = new FormUrlEncodedContent(requestData)
};
request.Headers // Add or modify headers
var response = await client.SendAsync(request);
// To read the response as string
var responseString = await response.Content.ReadAsStringAsync();
// To read the response as json
var responseJson = await response.Content.ReadAsAsync<ResponseObject>();
Essentially you need use an instance of HttpClient to send an HttpRequestMessage to an endpoint.
Here is an example to post some jsonData to someEndPointUrl:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, someEndPointUrl);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request, CancellationToken.None);
var str = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
// handle your response
}
else
{
// or failed response ?
}

POST Request with json in c#

I am attempting to do a POST request which I have got working through Postman but I am getting a 400 error when done from code.
I am trying to reach the POST endpoint from here: http://developer.oanda.com/rest-live-v20/order-ep/
Here is my code, does anything look incorrect or have I missed anything?
public void MakeOrder(string UID)
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer 11699873cb44ea6260ca3aa42d2898ac-2896712134c5924a25af3525d3bea9b0");
client.Headers.Add("Content-Type", "application/json");
client.UploadString(url, body);
}
}
I'm very new to coding so apologies if it is something very simple.
use HttpClient from System.Net.Http:
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body , Encoding.UTF8, "application/json");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}
I would suggest you to use HttpClient over WebClient. You can find here the difference.
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTIzMDY0NTQsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.c-3boD5NtOEhXNUnzPHGD4rY1lbEd-pjfn7C6kDPbxw");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}

write a http post request to bot framework running on localhost

I have a bot running on http://localhost:3978/api/messages.
Instead of debugging it using an emulator, can I go about using a http post request to the messaging endpoint of the bot?
If so, how do I go about doing it?
I am using c# microsoft bot framework, and I am new to this application.
I do not want to use any channels or DirectLine api, just using Httpclient.
You can do this with C# using code similar to below. Note that you would have to construct an Activity to send by setting the appropriate properties for your needs, which is not included in this code.
//make a call to get an auth token
string token;
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["grant_type"] = "client_credentials";
values["client_id"] = "YOUR APP ID";
values["client_secret"] = "NcOXRwb51joibEfzUuNE04u";
values["scope"] = "YOUR APP ID/.default";
var response =
client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);
var responseString = Encoding.Default.GetString(response);
var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
token = result.access_token;
}
//you will need to adjust this value for your project.
//this example for a proxy project so the service url here is
//just an arbitrary endpoint I was using to send activities to
activity.ServiceUrl = "http://localhost:4643/api/return";
var jsonActivityAltered = JsonConvert.SerializeObject(activity);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", $"Bearer {token}");
try
{
var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Have you tried using something like postman? (it's free and easy to use)
https://www.getpostman.com/
You can also write scripts in postman
otherwise you can just go to the endpoint of your API in the browser
http://localhost:3978/api/
I see you mentioned you wanted to make a console application.
You could do that. I'd suggest using postman though.
Here is an example of sending a file as well as some querystring data and Authentication using a Bearer token.
Sorry it may not be exact. Had to do a bit of copy pasting/deleting from some code examples if have
using (HttpClient client = new HttpClient())
{
JObject jsonModel = new JObject();
client.BaseAddress = new Uri("http://localhost:3978/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("firstname", lastname),
new KeyValuePair<string, string>("lastname", lastname),
new KeyValuePair<string, string>("payloadFile", FileName)
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
ByteArrayContent fileContent = new ByteArrayContent(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
string FullxmlString = File.ReadAllText(Path.Combine(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("payloadFile") { FileName = "payloadFile" };
multipartFormDataContent.Add(fileContent);
HttpResponseMessage response = client.PostAsync("api/message", multipartFormDataContent).Result;
string returnString = response.Content.ToString();
using (HttpContent content = response.Content)
{
string res = "";
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
}
}

Set Authorization/Content-Type headers when call HTTPClient.PostAsync

Where can I set headers to REST service call when using simple HTTPClient?
I do :
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{"id", "111"},
{"amount", "22"}
};
var content = new FormUrlEncodedContent(values);
var uri = new Uri(#"https://some.ns.restlet.uri");
var response = await client.PostAsync(uri, content);
var responseString = await response.Content.ReadAsStringAsync();
UPD
Headers I want to add:
{
"Authorization": "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3",
"Content-Type": "application/json"
}
Should I do the following?
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json");
The way to add headers is as follows:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Or if you want some custom header:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE");
This answer has SO responses already, see below:
Adding headers when using httpClient.GetAsync
Setting Authorization Header of HttpClient
UPDATE
Seems you are adding two headerrs; authorization and content type.
string authValue = "NLAuth nlauth_account=5731597_SB1,nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3";
string contentTypeValue = "application/json";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);
I know this was asked a while ago, but Juan's solution didn't work for me.
(Also, pretty sure this question is duplicated here.)
The method that finally worked was to use HttpClient with HttpRequestMessage and HttpResponseMessage.
Also note that this is using Json.NET from Newtonsoft.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace NetsuiteConnector
{
class Netsuite
{
public void RunHttpTest()
{
Task t = new Task(TryConnect);
t.Start();
Console.WriteLine("Connecting to NS...");
Console.ReadLine();
}
private static async void TryConnect()
{
// dummy payload
String jsonString = JsonConvert.SerializeObject(
new NewObj() {
Name = "aname",
Email = "someone#somewhere.com"
}
);
string auth = "NLAuth nlauth_account=123456,nlauth_email=youremail#somewhere.com,nlauth_signature=yourpassword,nlauth_role=3";
string url = "https://somerestleturl";
var uri = new Uri(#url);
HttpClient c = new HttpClient();
c.BaseAddress = uri;
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
req.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await c.SendAsync(req);
httpResponseMessage.EnsureSuccessStatusCode();
HttpContent httpContent = httpResponseMessage.Content;
string responseString = await httpContent.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
class NewObj
{
public string Name { get; set; }
public string Email { get; set; }
}
}
The other answers do not work if you are using an HttpClientFactory, and here's some reasons why you should. With an HttpClientFactory the HttpMessages are reused from a pool, so setting default headers should be reserved for headers that will be used in every request.
If you just want to add a content-type header you can use the alternate PostAsJsonAsync or PostAsXmlAsync.
var response = await _httpClient.PostAsJsonAsync("account/update", model);
Unfortunately I don't have a better solution for adding authorization headers than this.
_httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");
On dotnet core 3.1 trying to run the top answer:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", "application/x-msdownload");
threw an exception: System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
What worked for me was to instead set HttpContent.Headers -> HttpContentHeaders.ContentType property with a MediaTypeHeaderValue value:
HttpClient client = new HttpClient();
var content = new StreamContent(File.OpenRead(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-msdownload");
var post = client.PostAsync(myUrl, content);
I prefer to cache the httpClient so I avoid setting headers which could affect other requests and use SendAsync
var postRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
postRequest.Headers.Add("Content-Type", "application/x-msdownload");
var response = await httpClient.SendAsync(postRequest);
var content = await response.Content.ReadAsStringAsync();

500 Server Error when calling REST API over HTTPS

I'm using this code to POST XML to a REST webservice, but am just getting a vague '500 Server Error'. If I paste the same XML into Fiddler it works perfectly, so what am I doing wrong?
using (var client = new HttpClient())
{
var httpContent = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
var response = client.PostAsync(new Uri("httpsapiurl"),httpContent).Result;
if (response.IsSuccessStatusCode)
{
// EDITED: this isn't hit as IsSuccessStatusCode is always false
//Stream stream = await response.Content.ReadAsStreamAsync();
}
}
Could it be that you need to set the Content type on the request?
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, URL);
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
await httpClient.SendAsync(req).ContinueWith(async respTask =>
{
Debug.WriteLine(req.Content.ReadAsStringAsync());
};
}
catch (Exception ex)
{
}
Especially this line is important. I had similar problem with an API that refused to spit anything back when not setting the Content-Type header correct.
req.Content = new StringContent(doc.ToString(), Encoding.UTF8, "text/xml");
Don't know if it can help.

Categories

Resources