i have a simple demo winform app and im trying to make a post request with header to web api.
i received access token and refreash token form the server and i stored that in text file.
and im trying to make a post request by sending the refreash token with the body and sending the access token with the header but i dont know how to include the header with the post request.
this my post method
public static async Task<string> sendMessage(string name, string contents)
{
using (HttpClient client = new HttpClient())
{
//reading the access token and refreash token from file
StreamReader sr = new StreamReader(#"C:\Users\noorm\Desktop\noor.txt");
string accessToken, refreashToken;
accessToken = sr.ReadLine();
refreashToken = sr.ReadLine();
//defining new instance of message opject
var newMessage = new messages()
{
name = name,
content = contents,
refreashToken = refreashToken
};
//sening the opject using post async and returning the response
var newPostJson = JsonConvert.SerializeObject(newMessage);
var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await client.PostAsync(baseURL + "/messages", payLoad))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
and this is the button
private async void btnSend_Click(object sender, EventArgs e)
{
var responce = await restHelper.sendMessage(txtName.Text.Trim(),txtContent.Text.Trim());
rtxt.Text = responce;
}
You can try something like the following:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
this is how i was able to send the access token with the header
client.DefaultRequestHeaders.Add("x-auth-token", accessToken);
Related
I have created an API, which shall have the capability to connect to en external API via POST and with a request body in form of a string.
I am able to connect directly to the API from Postman without trouble.. But it does not work via my own API.
Any ideas?
This is the Pastebin.
private string EncodeExternalApiLink = "https://blabla.dk";
private string EncodeExternalApiLinkPostFilter = "searchstring/blabla/api/search";
[HttpPost("getdata/filtered")]
public async Task<IActionResult> GetDataFromExternalFiltered([FromBody] string filter)
{
var filterString = new StringContent(filter);
EncodeExternalToken token = GetExternalToken().Result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(EncodeExternalApiLink);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);
using (var response = await client.PostAsync(EncodeExternalApiLinkPostFilter, filterString))
{
return Json(response);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return Content(content, "application/json");
}
else
{
return NotFound();
}
}
}
}
Salutations. You might need to add a "/" to the end of your base address EncodeExternalApiLink or to the beginning of EncodeExternalApiLinkPostFilter.
I am trying to add members to an AD groups invoking Microsoft Graph API through an Azure Function
It is very easy and straightforward to execute GET requests through Graph API's, but I can't find any examples how I could execute post requests for the Graph API
I do have an example of a post request for the Graph API which is
POST https://graph.microsoft.com/v1.0/groups/{id}/members/$ref
Content-type: application/json
Content-length: 30
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/{id}"
}
Here is the code I successfully use to retrieve the Graph response
public static async Task<HttpResponseMessage> GetDirectoryUsers(string graphToken, TraceWriter log, string displayName)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
string requestUrl = "https://graph.microsoft.com/v1.0/groups?$top=2&$filter=displayName eq '" + displayName + "'&$expand=Members";
var request = new HttpRequestMessage(new HttpMethod("GET"), requestUrl);
var response = await client.SendAsync(request);
return response;
}
However, I am completely lost how I could execute the request through a C# code within the Azure function to ADD the retrieved users to another AD. How can construct the request URL? How should I handle the odata id within that request URL?
If anyone could help me in any way, I would greatly appreciate it
A reuse method for add sub-group/member to group(O365 doesn't support add sub-group to group now)
/// <param name="graphClient"></param>
/// <param name="groupId"></param>
/// <param name="memberId">memberId/sub-group id</param>
/// <returns></returns>
public static async Task AddGroupMember1(GraphServiceClient
graphClient, string groupId, string memberId)
{
User memberToAdd = new User { Id = memberId };
//Group memberToAdd= new Group { Id = memberId };
await graphClient.Groups[groupId].Members.References.Request().AddAsync(memberToAdd);
}
Here is the answer that worked for me
public static async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
var status = string.Empty;
try
{
string endpoint = "https://graph.microsoft.com/v1.0/groups/" + groupId + "/members/$ref";
string queryParameter = "";
// pass body data
var keyOdataId = "#odata.id";
var valueODataId = "https://graph.microsoft.com/v1.0/directoryObjects/" + memberId;
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(keyOdataId, valueODataId)
};
var jsonData = $#"{{ ""{keyOdataId}"": ""{valueODataId}"" }}";
var body = new StringContent(jsonData, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter))
{
request.Content = body;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.NoContent)
status = "Member added to Group";
else
status = $"Unable to add Member to Group: {response.StatusCode}";
}
}
}
}
catch (Exception ex)
{
status = $"Error adding Member to Group: {ex.Message}";
}
return status;
}
I'm using graph api for sending email. The code in below
public async Task<dynamic> SendMail(string accessToken, MailWrapper mail)
{
try
{
GraphServiceClient graphClient = SDKHelper.GetMicrosoftAuthenticatedClient(accessToken);
Message message = await BuildEmailMessage(graphClient, mail);
await graphClient.Me.SendMail(message, true).Request().PostAsync(CancellationToken.None);
var response = await graphClient.Me.MailFolders.SentItems.Messages.Request()
.OrderBy(sendDateTimeDesc)
.Top(1)
.GetAsync();
return await Task.FromResult(response);
}
catch (ServiceException ex)
{
throw ex;
}
}
Assembly Microsoft.Graph, Version=1.9.0.0
That's what worked for me
public void AddUserToGroup(string groupId)
{
var requestUri = $"{_graphApiUrl}/v1.0/groups/{groupId}/members/$ref";
var id = "user_id";
var OdataId = "#odata.id";
var ODataValue = $"https://graph.microsoft.com/v1.0/users/{id}";
var content = $#"{{ ""{OdataId}"": ""{ODataValue}"" }}";
using (var httpClient = new HttpClient())
using (var httpRequest = CreateHttpRequest(HttpMethod.Post, requestUri, content))
{
var response = httpClient.SendAsync(httpRequest).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
var reason = $"Status code: {(int)response.StatusCode}, Reason: {response.StatusCode}";
throw new Exception(reason);
}
}
}
And important thing was when creating a request to use:
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
it didn't work with:
request.Content = new StringContent(content);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
I want to post a message to slack on x channel I need to send the following x parameters how do I send the following parameters to a website
"channel": "XXXXX", "token": "token", "text": "text"
I am coding in c# mvc application.
public async Task<HttpResponseMessage> SendMessageAsync(string message, string channel = null, string userName = null)
{
using (var client = new HttpClient())
{
string url = "https://fake2604.slack.com/api/chat.postMessage?token=myToken&channel=" + channel + "&text=Hello World";
var payLoad = new
{
text = message,
channel,
userName,
};
var serializedPayload = JsonConvert.SerializeObject(payLoad);
var response = await client.PostAsync(url, new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
This is not working.It just adds an integration to the channel that I select in the OAuth page which again I got through Add to Slack button.
I suppose the problem is with your webhook url which you are adding some more stuff to that.this code definitely work:
public async Task<HttpResponseMessage> SendMessageAsync(string message)
{
var payload = new
{
text = message,
channel="x",
userName="y",
};
HttpClient httpClient = new HttpClient();
var serializedPayload = serializer.ToJson(payload);
var response = await httpClient.PostAsync("url",
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
I am making HTTP Post call to a webservice url. In the response I get 200 Status Ok message. But when I try to get the response content using await response.Content.ReadAsStringAsync() its always '{}'. The web service returns either SUCCESS or FAILED based on the user credentials passed. How do I retrieve the message. Please help.
Code to make a web service call
public Task<HttpResponseMessage> PostAsJsonAsync<T>(Uri uri, T item)
{
var client = new HttpClient();
var itemAsJson = JsonConvert.SerializeObject(item);
var content = new StringContent(itemAsJson);
//var content = new FormUrlEncodedContent(itemAsJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Clear();
return client.PostAsync(uri, content);
}
private async void mainPage_Loaded(object sender, RoutedEventArgs e)
{
UserDetails details = new UserDetails()
{
username = composite["username"].ToString(),
userpass = composite["password"].ToString()
};
var response = await PostAsJsonAsync(new Uri("http://ec2-xxxx-.compute-1.amazonaws.com:8080/Sanjeevani/rest/SV/login"), details);
if (response.IsSuccessStatusCode) //I get a 200 code i.e OK
{
string str = await response.Content.ReadAsStringAsync();
if (str == "SUCCESS") //str is always '{}'
{
this.Frame.Navigate(typeof(Dashboard), details);
}
}
I writing UWP app.
I need to send POST request with json to server
Here is my code for downloading JSON and writing to value:
public async void AllOrders_down()
{
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
var json = await FetchAsync(url);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
OrdersList = new List<RootObject>(rootObjectData);
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
How I need to send POST request with this json to server?
Thank's for help.
Here is an example Post request that I have used in a UWP application.
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://test.com/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/api/testendpoint";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
You should be using httpClient.PostAsync().