Calling WebApi with complex object parameter using WebClient - c#

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.

You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference

Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}

Related

How to do a Post using WebRequest from a Class Library?

I want to call to a API using a class library.
Here is the way they need us to send the post request
Or
To achecive this I use this code
public class Keey
{
public string username { get; set; }
public string passward { get; set; }
public string src { get; set; }
public string dst { get; set; }
public string msg { get; set; }
public string dr { get; set; }
}
public void SendSms(string phoneNo, string SMS)
{
Keey account = new Keey
{
username = "*****",
passward = "*********",
src = "test.com",
dst = phoneNo,
msg = SMS,
dr = "1",
};
WebRequest request = WebRequest.Create("http://testserver.com ");
// Set the Method property of the request to POST.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = SMS.Length;
CredentialCache.DefaultNetworkCredentials.UserName = account.username;
CredentialCache.DefaultNetworkCredentials.Password = account.passward;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
WebResponse response = request.GetResponse();
}
But I dont know where to add those port,src,dst,msg etc... Please help me
Code is in C#
That is depend on your Web-Api Service. for what input parameter needed.
There are several ways to perform POST requests:
HttpWebRequest (not recommended for new work)
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
var request = (HttpWebRequest)WebRequest.Create("http://testserver.com/test.aspx");
//your data should place in here
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
recommended way to get this work:
using System.Net.Http;
private static readonly HttpClient client = new HttpClient();
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://testserver.com/test.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

Receive API Response in c#

im trying to get a this value that i send with JSON string POST, when i receive the response in postman, there's value like status, id, etc that i not POST, while i do understand get the value from JSON string,
i dont quite understand to get a receive API value like status and Name
what i do tried recently
public class Condition
{
public string status { get; set; }
public string name { get; set; }
public string positition { get; set; }
public int no_id { get; set; }
public string time_auth { get; set; }
public string account_type { get; set; }
}
for the method
public partial class ResponseJSON
{
public bool Result(string jsonData, string URL, out string status)
{
bool resultresponse = false;
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
var writer = new StreamWriter(request.GetRequestStream());
string wrote = jsonData;
writer.Write(wrote);
var httpResponse = (HttpWebResponse)request.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var result = streamReader.ReadToEnd();
dynamic R = JsonConvert.DeserializeObject<dynamic>(wrote);
status = R.auth_type;
return resultresponse;
}
}
and for the main
string jsonData = #"{
'auth_type':'7',
'staff_id':'1234567890',
'staff_pin': '1234'}";
dynamic data = JObject.Parse(jsonData);
string URL = "Link URL";
string status = string.Empty;
ResponseJSON responseJSON = new ResponseJSON();
responseJSON.Result(jsonData, URL, out status);
You might want to declare the same class "Condition" on your client side, so you can deserialize the response with Newtonsoft with something like this:
var conditionResponse = JsonConvert.DeserializeObject<Condition>(jsonData);

Google vision connection to API without external google DLL

How to connect to google cloud vision without using external dlls?
First, you will have to generate JSON request, simple example:
Request req = new Request();
req.addFeature("DOCUMENT_TEXT_DETECTION"); //Add here all the feature types
req.Image.content = Convert.ToBase64String(qq);//qq is a byte[]
Requests reqList = new Requests(req);
json = JsonConvert.SerializeObject(reqList);
Secondly, you need to post simple HTTP request:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://vision.googleapis.com/v1/images:annotate?key="PLACE_YOURKEY_HERE"");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
Memebers of the JSON classes (The methods should be implemented):
class Requests
{
public List<Request> Request { get; set; }
}
class Request
{
public Image1 Image { get; set; }
public List<Feature> Features { get; set; }
}
public class Feature
{
public string Type { get; set; }
}
public class Image1
{
public string content { get; set; }
}
Relevant to the topic links
Google Vision API Document_Text_Detection
Feature types
Google vision

Problems with Getting Response on the deployed bot;

I've got some problems with getting REST API response that allows to get members of the group( GET {serviceUrl}/v3/conversations/{conversationId}/members). I'm debugging my bot in Bot Emulator, and it runs fine here
- that's what it shows in the Bot Simulator
- But that's how it shows on Azure.
The main problem is that i really can't recognize the problem.I know that the problem is in requesting because the getResponse method crash all programm when it is on server(but why this works in the bot emulator?).Here is the code(I'm using .NET CORE, Microsoft Bot Framework). P.S.{id} in Authorization is correct, and i get it from another request(but unlike the problem request that request works everywhere), the {url} is turnContext.Activity.ServiceUrl
HttpWebRequest webRequest23 = (HttpWebRequest)WebRequest.Create($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync($"{url}/v3/conversations/{turnContext.Activity.Conversation.Id}/members");
await turnContext.SendActivityAsync(turnContext.Activity.Conversation.Id);
webRequest23.ContentType = "application/json";
webRequest23.Headers["Authorization"] = $"Bearer {id}";
WebResponse response2 = webRequest23.GetResponse();//crash here
await turnContext.SendActivityAsync("3");
string smth25 = "";
using (StreamReader stream = new StreamReader(response2.GetResponseStream(), true))
{
smth25 = stream.ReadToEnd();
}
JArray jsonArray = JArray.Parse(smth25);
List<string> names = new List<string>();
foreach(var x in jsonArray)
{
var name = JObject.Parse(x.ToString())["name"].ToString();
names.Add("#" + name);
}
string s = "This group consists of - ";
foreach (var x in names){
s += "" + x + ",";
}
await turnContext.SendActivityAsync(s);
Here is how i get id:
string stringData = "grant_type=client_credentials&client_id=66b16ef5-d086-40b7-ae9c-2f50a1f028c6&client_secret=yRUYg4g.:ANuw3Y_01V=#.JkAv=#g3EE&scope=https%3A%2F%2Fapi.botframework.com%2F.default";
var data = Encoding.Default.GetBytes(stringData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
webRequest.Host = "login.microsoftonline.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
var newStream = webRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = webRequest.GetResponse();
string line = string.Empty;
string smone = "";
using (StreamReader stream = new StreamReader(response.GetResponseStream(), true))
{
smone = stream.ReadToEnd();
}
var id = JObject.Parse(smone)["access_token"].ToString();
I don't understand exactly what your "turnContext.SendActivityAsync" lines are supposed to do, but it might be working in the bot emulator because the emulator doesn't require a proper authenticated session like Teams does. Anyway, something like this should actually help you:
First, define this class somewhere:
public class MicrosoftTeamUser
{
public string Id { get; set; }
public string ObjectId { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string UserPrincipalName { get; set; }
public string TenantId { get; set; }
}
then use:
List<ChannelAccount> teamMembers = (await turnContext.TurnState.Get<IConnectorClient>().Conversations.GetConversationMembersAsync(
turnContext.Activity.GetChannelData<TeamsChannelData>().Team.Id).ConfigureAwait(false)).ToList();
List<MicrosoftTeamUser> teamsUsers = new List<MicrosoftTeamUser>();
foreach (var item in teamMembers)
{
var teamsUser = JsonConvert.DeserializeObject<MicrosoftTeamUser>(item.Properties.ToString());
teamsUser.Id = item.Id;
teamsUsers.Add(teamsUser);
}
Then you'll have the list of members in the teamMembers variable

iphone push notification urbanairship

i"m want to send notification from my server side (c#) via urbanairship api
is there any example in c# how to do it?
thanks
Basically...
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main ()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
broken out to multiple lines so you can read it
string postData = "{
"device_tokens": [
"some device token",
"another device token"
],
"aliases": [
"user1",
"user2"
],
"tags": [
"tag1",
"tag2"
],
"schedule_for": [
"2010-07-27 22:48:00",
"2010-07-28 22:48:00"
],
"exclude_tokens": [
"device token you want to skip",
"another device token you want to skip"
],
"aps": {
"badge": 10,
"alert": "Hello from Urban Airship!",
"sound": "cat.caf"
}
}";
and then
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "<application key from urban airship>";
string password = "<master secret from urban airship>";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add( new Uri( "https://go.urbanairship.com/api/push/" ), "Basic", new NetworkCredential( username, password ) );
request.Credentials = mycache;
request.Headers.Add( "Authorization", "Basic " + Convert.ToBase64String( new ASCIIEncoding().GetBytes( usernamePassword ) ) );
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}
See api docs, msdn and here for more on https
The accepted answer doesn't work, you need to change the following line:
request.ContentType = "application/x-www-form-urlencoded";
to
request.ContentType = "application/json";
Complete working code shown below:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace UrbanAirship_Tes_1
{
class Program
{
public static void Main()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
request.Credentials = new NetworkCredential("pvYMExk3QIO7p2YUs6BBkg", "rO3DsucETRadbbfxHkd6qw");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
//WRITE JSON DATA TO VARIABLE D
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"6334c016fc643baa340eca25bc661d15055a07b475e9a6108f3f644b15dd05ac\"]}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
// Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
public class PushNotificationHelper
{
private readonly ILog log4netEngine;
private string UrbanAirshipApplicationKey { get; set; }
private string UrbanAirshipApplicationSecret { get; set; }
private string UrbanAirshipApplicationMasterSecret { get; set; }
public PushNotificationHelper(string UrbanAirshipApplicationKey, string UrbanAirshipApplicationSecret, string UrbanAirshipApplicationMasterSecret)
{
log4netEngine = LogManager.GetLogger(typeof(PushNotificationHelper).Name);
this.UrbanAirshipApplicationKey = UrbanAirshipApplicationKey;
this.UrbanAirshipApplicationSecret = UrbanAirshipApplicationSecret;
this.UrbanAirshipApplicationMasterSecret = UrbanAirshipApplicationMasterSecret;
}
public void PushNotification2iPhones(string alertText, string[] apids, string extra)
{
if (!string.IsNullOrEmpty(alertText) && apids.Length > 0)
{
iPhonePushNotification pushNotification = new iPhonePushNotification
{
MessageBody = new iPhonePushNotificationMessageBody
{
Alert = alertText
},
Extra = extra,
APIDs = apids
};
string jsonMessageRequest = pushNotification.ToJsonString();
try
{
SendMessageToUrbanAirship(jsonMessageRequest);
log4netEngine.InfoFormat("Push Notification Success , iPhoneDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra);
}
catch (Exception ex)
{
log4netEngine.InfoFormat("Push Notification Error:{0}, iPhoneDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra);
}
}
}
public void PushNotification2Androids(string alertText, string[] apids, string extra)
{
if (!string.IsNullOrEmpty(alertText) && apids.Length > 0)
{
AndroidPushNotification pushNotification = new AndroidPushNotification
{
MessageBody = new AndroidPushNotificationMessageBody
{
Alert = alertText,
Extra = extra
},
APIDs = apids
};
string jsonMessageRequest = pushNotification.ToJsonString();
try
{
SendMessageToUrbanAirship(jsonMessageRequest);
log4netEngine.InfoFormat("Push Notification Success , androidDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra);
}
catch (Exception ex)
{
log4netEngine.InfoFormat("Push Notification Error:{0}, androidDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra);
}
}
}
private void SendMessageToUrbanAirship(string jsonMessageRequest)
{
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = WebRequest.Create(uri);
request.Method = "POST";
request.Credentials = new NetworkCredential(this.UrbanAirshipApplicationKey, this.UrbanAirshipApplicationMasterSecret);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(jsonMessageRequest);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(jsonMessageRequest), 0, encoding.GetByteCount(jsonMessageRequest));
stream.Close();
var response = request.GetResponse();
response.Close();
}
}
}
public class NotificationToPush
{
public int ReceiverUserID { get; set; }
public string Message { get; set; }
public Dictionary<string, string> Extra { get; set; }
}
[DataContract(Name = "PushNotificationBody")]
internal class PushNotification
{
public string ToJsonString()
{
var result = JsonConvert.SerializeObject(this);
return result;
}
}
[DataContract(Name = "iPhonePushNotification")]
internal class iPhonePushNotification : PushNotification
{
[DataMember(Name = "aps")]
public iPhonePushNotificationMessageBody MessageBody { get; set; }
[DataMember(Name = "extra")]
public string Extra { get; set; }
[DataMember(Name = "device_tokens")]
public string[] APIDs { get; set; }
}
[DataContract(Name = "iPhonePushNotificationMessageBody")]
internal class iPhonePushNotificationMessageBody
{
[DataMember(Name = "alert")]
public string Alert { get; set; }
}
[DataContract(Name = "AndroidPushNotification")]
internal class AndroidPushNotification : PushNotification
{
[DataMember(Name = "android")]
public AndroidPushNotificationMessageBody MessageBody { get; set; }
[DataMember(Name = "apids")]
public string[] APIDs { get; set; }
}
[DataContract(Name = "AndroidPushNotificationMessageBody")]
internal class AndroidPushNotificationMessageBody
{
[DataMember(Name = "alert")]
public string Alert { get; set; }
[DataMember(Name = "extra")]
public string Extra { get; set; }
}
Here is how to do it using the System.Net.Http.HttpClient async methods.
var handler = new HttpClientHandler { Credentials = new NetworkCredential(urbanairshipapiKey, urbanairshipApiAppMasterSecret) };
var client = new HttpClient(handler);
var added = client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/vnd.urbanairship+json; version=3;");
var response = await client.PostAsync(apiUrl + "/push/", new StringContent(json, Encoding.UTF8, "application/json"));
I wrote a c# library to simplify the use of the UrbanAirship API
https://github.com/JeffGos/urbanairsharp
Hope it helps!

Categories

Resources