I have fetch channel history in my .Net Web API.
The slack reference https://api.slack.com/methods/channels.history it states that we need to post the request.
Please if someone could help me with the code.
Part of Code I have implemented:
#region create json payload to send to slack
GetLatestMessage payload = new GetLatestMessage()
{
channel = "###",//value.channel_name,
token = "############################"//added the token i have generated
// user_name = value.user_name,
//text = value.text
};
#endregion
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
I figured out the issue I was facing.I was trying to sent the post json data in to Slack url. However The Slack Web API doesn't accept JSON data.Now when I post data using standard HTTP form attributes it accepts and returns proper response.
New code:
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", new NameValueCollection() {
{"token","###################"},
{"channel","######"}});
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
Related
I am creating prototype of application where in I am trying to send data in request header and body from C# MVC Controller and also created web api project Post action to process the request.
My code goes like this::
MVC Project code to Post Request:
public class HomeController : Controller
{
public async Task<ActionResult> Index()
{
VM VM = new VM();
VM.Name = " TEST Name";
VM.Address = " TEST Address ";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:58297");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("username","test");
var json = JsonConvert.SerializeObject(VM);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var result1 = await client.PostAsync("api/Values/Post", content);
}
return View();
}
}
My code in WEB API project :
// POST api/values
public IHttpActionResult Post([FromBody]API.VM vm)
{
try
{
HttpRequestMessage re = new HttpRequestMessage();
StreamWriter sw = new StreamWriter(#"E:\Apple\txt.log", false);
var headers = re.Headers;
string token = "";
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
sw.WriteLine("From header" + token);
sw.WriteLine("From BODY" + vm.Name);
sw.WriteLine("From BODY" + vm.Address);
sw.WriteLine("Line2");
sw.Close();
return Ok("Success");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
What I have understood is [FromBody]API.VM vm gets data from Http request body which means vm object is getting data from HTTP Request body.I am able to get request body. I am not able to understand how do I pass data in header from MVC controller (I want to pass JSON Data) and retrieve data in WEB Api post method?
I have used client.DefaultRequestHeaders.Add("username","test"); in MVC project to pass header data and
HttpRequestMessage re = new HttpRequestMessage();
var headers = re.Headers;
string token = "";
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
in WEB API project to get data but I am not able to get username value.
In order to get your data via headers, you would need to enable CORS: Install-Package Microsoft.AspNet.WebApi.Cors in your project and then in your Register method under WebApiConfig.cs, add this line: EnableCors();.
Once done, you can access your header variable as:
IEnumerable<string> values = new List<string>();
actionContext.Request.Headers.TryGetValues("username", out values);
You can get all headers being passed to a method of a web API using below lines inside that web API method:
HttpActionContext actionContext = this.ActionContext;
var headers = actionContext.Request.Headers;
I have a API in C# and another one in Visual Basic. I need to send some information in JSON format from the API in C# to the API in Visual Basic, hopefully using POST verb. The context of the situation is like this. A mobile application send information to the API in C#, the API save the data in a database located in the server, then if the information is correct the API in C# have to send the data to the Visual Basic API and save it in other server. Anybody knows hoy to send the data from C# to Visual Basic? Thanks.
It doesn't matter that one API is in C# and the other in VB. As long as the json you are sending is valid (try validating the json you send at jsonlint.com) and can be mapped to an object the API accepts everything should be fine.
It seems like the endpoint api is not accepting the request.
This is my C# code
try
{
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
var1 = "example1",
var2 = "example2"
});
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return Request.CreateResponse(HttpStatusCode.OK, new { Respuesta = result }, "application/json");
}
}
catch(Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, new { Respuesta = e.ToString() }, "application/json");
}
}
And this is my function in Visual Basic
Public Function PostValue(ByVal json as String)
return json
End Function
Thats all. And throw me this error
{
"Respuesta": "System.Net.WebException: The remote server returned an error: (404) Not Found.\r\n at System.Net.HttpWebRequest.GetResponse()\r\n at Servicios.Controllers.SAPEnviarFacturasController.SAPEnviarFacturas() in C:\TFS\Servicios\Controllers\SAPEnviarFacturasController.cs:line 44"
}
I'm working on a windows store app where I am using a web service which has parameters for downloading videos that are given below.
[request addValue:Token Id forHTTPHeaderField:#"Authorization"];
Through log_in web services I get the access token which I have to pass as value in the Authorization a request to the HTTP Header.
Token token="hgmgmhmhgm6dfgffdbfetgjhgkj4mhh8dghmge"
I have to send both these parameters with the web service given to me but I am unable to send them as I'm getting the error status code 404 unauthorized.
Here is my code:
System.Net.Http.HttpClient httpClient1 = new System.Net.Http.HttpClient();
httpClient1.DefaultRequestHeaders.Date = DateTime.Now;
httpClient1.DefaultRequestHeaders.Add("Authorization",acesstoken);
var httpResponse1 = await httpClient.GetAsync("http://gbdfbbnbb#gfdh.co/appi/fdbfdses/3/videos");
string vale = await httpResponse1.Content.ReadAsStringAsync();
string responses = vale;
I know my code is wrong and I need to correct it. Help me with your valuable suggestions.
Try this code
using (var client = new HttpClient())
{
try
{
String url = "https://www.example-http-request.com/json";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Authorization", acesstoken)
};
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responsesStr = await response.Content.ReadAsStringAsync();
if (!responsesStr.Equals(""))
{
//http request data now capture in responseToken string.
//you can change name as per your requirement.
String responseOutput = responsesStr;
//now convert/parse your json using Newtonsoft JSON library
// Newtonsoft JSON Librar link : { http://james.newtonking.com/json }
//LoggingModel is a class which is the model of deserializing your json output.
LoggingModel array = JsonConvert.DeserializeObject<LoggingModel>(responseOutput);
bool isSuccess = array.IsSuccessful;
if (isSuccess == true)
{
//if success
}else{
//if login failed
}
}else{
//no response in http request failed.
}
}
catch (Exception ex)
{
//catch exceptio here
}
}
UPDATE: I figured it out and posted the answer below.
All I'm trying to do is update any file attribute. Description, name, anything, but no matter how I format it I get a 403.
I need to be able to modify a file so it can be shared via the Box API from a cloud app. I'm updating someone else's code from V1, but they are no longer available... I've tried many things but mostly just get 403 Forbidden errors.
There are no issues with OAuth2, that works fine and I can list files and folders, but can not modify them. This question is about sharing, but I can't change a description either. The box account is mine and I authenticate with my admin credentials. Any suggestions would be appreciated.
Here is the method I am using. I pass in the fileId and token and I've left out try/catch etc. for brevity.
string uri = string.Format("https://api.box.com/2.0/files/{0}", fileId);
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Authorization: Bearer " + token);
var response = client.UploadData(uri, postArray);
var responseString = Encoding.Default.GetString(response);
}
Thanks.
Okay, My Homer Simpson moment...
UploadData is a POST, I needed to do a PUT. Here is the solution.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;
try changing your content type to 'multipart/form-data'?
I just looked up the api at: https://developers.box.com/docs/#files-upload-a-file
and it looks like the server is expecting a multipart post
here is stack overflow post on posting multipart data:
ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
I am trying to use RestSharp Api to use GustPay Api. I am confused how to pass “api_key” and “api_secret” in request.
var client = new RestClient("https://www.gustpay.com/api/gust_pass_venue_assignment");
var request = new RestRequest(Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddBody(request.JsonSerializer.Serialize(new
{
venue_name = "Cape Town Stadium",
latitude = "-33.903441",
longitude = "18.41113"
}));
var response = client.Execute(request);
Console.WriteLine(response.Content);
You should be able to use request.AddParameter(...). Call it once for each of your three parameters: api_key, api_secret, and data.
Edited to add: RestSharp will add these parameters to the body of the request because it's a POST request. It would add them to the querystring instead if it were a GET requests, but that's not the case in your example.