Consume Third Party Service in MVC 4 Razor View in .Net - c#

I have MVC 4 project developed in visual studio 2013 ,and i also have data in third party service,like
http://245.245.245.245/testapi/Service1.svc?wsdl
How i integrate the Third Party Service in my MVC Controller and Display it on Razor Views(.cshtml).
Give Suggestion code or any examples...

You can consume service by adding service reference in your web project. Its methods will be available and you will be able to call those methods within your web project.
If by some security reasons, you are unable to consume this directly, you can use HttpWebRequest:
var address = new Uri("https://yourServiceAddress");
var request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
//Your parameters that you need to pass
var requestObject = new RequestJson()
{
userName = username,
password = password
};
var requestJson = JsonConvert.SerializeObject(requestObject);
var byteData = Encoding.UTF8.GetBytes(requestJson);
request.ContentLength = byteData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteData, 0, byteData.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
}

Using add web reference you can access the service functionalities
I hope the following post help you Add Web Reference

Related

How to get response of AWS for upload link in ASP.NET Core?

I want to implement uploading images from Client-Side directly to an AWS S3 bucket.
I found a good tutorial in YouTube that show how to do it. Tutorial Link
But it's just for JavaScript.
I writing my program using ASP.NET core & I don't have any idea how to get the link from the AWS on the Back-End.
If you have done something similar, It would be great to share it with us.
Please, remember about limitations:
https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
https://docs.aws.amazon.com/AmazonS3/latest/userguide/PresignedUrlUploadObject.html
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetPreSignedUrlRequest.html
This final example creates a URL that allows a third party to put an object, then uses it to upload sample content. The URL is set to expire in 10 days.
GetPreSignedURL sample 5
// Create a client
AmazonS3Client client = new AmazonS3Client();
// Create a CopyObject request
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
{
BucketName = "SampleBucket",
Key = "Item1",
Verb = HttpVerb.PUT,
Expires = DateTime.UtcNow.AddDays(10)
};
// Get path for request
string path = client.GetPreSignedURL(request);
// Prepare data
byte[] data = UTF8Encoding.UTF8.GetBytes("Sample text.");
// Configure request
HttpWebRequest httpRequest = WebRequest.Create(path) as HttpWebRequest;
httpRequest.Method = "PUT";
httpRequest.ContentLength = data.Length;
// Write data to stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
// Issue request
HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;

access site and get a search result

I need to access www.skyscanner.com and get the answer to search (set in console application )
I try
var url= #"www.skyscanner.com";
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
using (var streamWriter = new StreamWriter(webRequestLogin.GetRequestStream()))
{
var httpResponsee = (HttpWebResponse)webRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponsee.GetResponseStream()))
{
var response = streamReader.ReadToEnd();
}
}
But i have one error "500", how i can access the site and make a search and get the result?.
Thank's
It doesn't look like your POST request has any payload. Skyscanner's server is probably expecting the itinerary details and since it is not getting them it is throwing the 500 error.
I have to add that what you are doing is not the proper way to interact with Skyscanner's service. They have an official API available for which you will need to register and get an API key here: http://business.skyscanner.net/portal/en-GB/AffiliateNetwork
You will then be able to make your application send requests to http://partners.api.skyscanner.net/apiservices/pricing/v1.0, as documented here:
http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingList

How to call POST RESTFUL service thru Console application

I have a rest ful service (POST) which accepts Json object as an input (Request body in Fiddler). Now I wanted to consume the service from Console Applciation with dynamic values (either read from text file or hardcoded values). I will log the actions like, for this test data XXXXX, the service returns values.
Can any one help me how to automate this process. I wold like to comsume this service from Console application.
Pls note Output also JSON string.
Any suggestion will be really helpful for me.
To make the POST request, something like:
var req = WebRequest.Create(url);
var enc = new UTF8Encoding(false);
var data = enc.GetBytes(serializedJson);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = data.Length;
using (var sr = req.GetRequestStream())
{
sr.Write(data, 0, data.Length);
}
var res = req.GetResponse();
var res= new StreamReader(res.GetResponseStream()).ReadToEnd();
You can easily create the serializedJson from an object like:
var serializedJson = Newtonsoft.Json.JsonConvert.SerializeObject(myDataObject);
Install the following web api package from nuget in your console project
Add a reference to System.Net.Http and System.Runtime.Serialization
Create a contract class of the data you want to send and receive (the same as in your webservice)
[DataContract]
public class YourObject{
[DataMember]
public int Id {get; set;}
}
In your console app call the webservice like this:
var client = new HttpClient();
var response = client.PostAsJsonAsync<YourObject>("http://yourserviceurl:port/controller", objectToPost).Result;
if(response.IsSuccessStatusCode){
Console.WriteLine(response);
}else{
Console.WriteLine(response.StatusCode);
}
More info about webapi here and here

Send Message using a WebRequest and Twilio

I'm need to send a message using Twilio services and the NetDuino.
I know there is an API that allows to send messages but it uses Rest-Sharp behind the scene which is not compatible with the micro-framework. I have try to do something like the below but I got a 401 error (not authorized). I got this code form here (which is exactly what I need to do)
var MessageApiString = "https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/SMS/Messages.json";
var request = WebRequest.Create(MessageApiString + "?From=+442033*****3&To=+447*****732&Body=test");
var user = "AC4*************0ab05bf";
var pass = "0*************b";
request.Method = "POST";
request.Credentials = new NetworkCredential(user, pass);
var result = request.GetResponse();
Twilio evangelist here.
From the code above it does not look like you are replacing the {AccountSid} token in the MessageApiString variable with your actual Account Sid.
Also, it looks like you are appending the phone number parameters to the URL as querystring values. Because this is a POST request I believe you need to include these as the request body, not in the querystring, which means you also need to set the ContentType property.
Here is an example:
var accountSid = "AC4*************0ab05bf";
var authToken = "0*************b";
var MessageApiString = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/SMS/Messages.json", accountSid);
var request = WebRequest.Create(MessageApiString);
request.Method = "POST";
request.Credentials = new NetworkCredential(accountSid, authToken);
request.ContentType = "application/x-www-form-urlencoded";
var body = "From=+442033*****3&To=+447*****732&Body=test";
var data = System.Text.ASCIIEncoding.Default.GetBytes(body);
using (Stream s = request.GetRequestStream())
{
s.Write(data, 0, data.Length);
}
var result = request.GetResponse();
Hope that helps.

rest api is not giving desired results

I am not getting the results that documentation says. I login the Buddy; created application; copy this URL and assign to url string; when I execute the program I am not getting results that are expected (status + Accesstoken) as documentation says. Can anyone please tell me if I am missing something as newbie to http calls. Its running on http requester but not on Poster firefox add-on!
Documentation
http://dev.buddyplatform.com/Home/Docs/Getting%20Started%20-%20REST/HTTP?
Code
string parameters = "{appid:'xxxxxx', appkey: 'xxxxxxx', platform: 'REST Client'}";
private async void SimpleRequest()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse) await request.GetResponseAsync();
}
catch (Exception)
{ }
}
Using the HTTP requester add-on on Firefox, I successfully retrieved an access token so their API work.
In C# they provide a line of code to submit your appid and appkey, that might be the problem :
Buddy.Init("yourAppId", "yourAppKey");
My guess is you have to use their .NET SDK!
You can certainly use the REST API from raw REST the way you're doing, though the .NET SDK will handle some of the more complex details of changing service root. I ran your code using my own Buddy credentials and I was able to get JSON containing an Access Token back. You may need to read the response stream back as JSON to retrieve the access token. I used the following code to dump the JSON to the console:
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
Console.WriteLine(await new StreamReader(response.GetResponseStream()).ReadToEndAsync());
Using Newtonsoft.Json I can parse out my accessToken like this:
Uri url = new Uri("https://api.buddyplatform.com/devices");
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
var parsed = JsonConvert.DeserializeObject<IDictionary<string,object>>( (await new StreamReader(response.GetResponseStream()).ReadToEndAsync()));
var accessToken = (parsed["result"] as JObject).GetValue("accessToken").ToString();
Console.WriteLine(accessToken);
The 3.0 SDK does all of this for you while exposing the rest of the service through a thin REST wrapper, the migration guide for the 3.0 SDK should help with this.

Categories

Resources