Basically my idea is to develop a proxy which will run in windows
I have created windows service application which running successfully and i have integrated a web service code in the windows service application running in windows service.
How to call that web service method when the client hits my url?
How to form the url which can call web service method to get the method return value?
OK, I'll try to answer.
Let's assume you want to call REST web service. What do you need? A HttpClient and (probably) JSON/XML Serializer. You can use built-in .NET classes, or a library like RestSharp
Sample calling REST web service using RestSharp
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
You are not required to use RestSharp, no. For simple cases HttpWebRequest (+DataContractJsonSerializaer or Xml analogue) will be just perfect
Having SOAP web service?
Follow the instructions provided here
Related
I have the wsdl of a web soap service and I have added it as a service reference with visual studio. I have notice that it doesn't have a request class for a method which I need to use. The reason I need it is because I have to store that request as xml and I have always used the request class to serialize. Is there a way to generate that request xml?
Simple representation:
var client = new SoapServiceCliente();
var request = new RequestClass(); <-- This is what soap service is missing.
var response = new ResponseClass();
response = client.theMethod(request);
Before calling the method I serialize the request to xml and after getting the response I serialize it too.
I'm sending data via GRPC to, let's call it, IntegrationApi, calling a method Foo. I need to read header values from the response (the API I'm communicating with sends rate-limiting headers).
I'm using https://www.nuget.org/packages/Grpc.Core/
var metaData = new Metadata();
metadata.Add(new Metadata.Entry("Authorization", $"Bearer {apiKey}"));
var channel = new Channel("url to endpoint", new SslCredentials());
var client = new IntegrationApi(channel);
var callOptions = new CallOptions()
.WithHeaders(metadata)
.WithDeadline(DateTime.UtcNow.AddSeconds(15))
.WithWaitForReady(false);
var response = client.Foo(req, options);
but the response only gives me the properties based on the Foo.proto file.
How do I do this?
You are using the synchronous version of "Foo" method, and that one uses a simplified version of the API (=only allows access to the response and throws RpcExceptions in case of an error).
If you call the asynchronous version of the same method ("FooAsync"), you'll get back a call object that can access all the call details (such as response headers).
https://github.com/grpc/grpc/blob/044a8e29df4c5c2716c7e8250c6b2585e1c425ff/src/csharp/Grpc.Core.Api/AsyncUnaryCall.cs#L73
I am calling an Restful API that expects me to pass a parameter callback(a URL)when doing POST.
The tool that I am using to make the call is RESTSharp. I have written the below code
var client = new RestClient("https://services.mywebsite.com/api/v3/");
client.Authenticator = new HttpBasicAuthenticator("Usernamae", "P2$$w0rd");
var request = new RestRequest("myAction", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddParameter("Id", "sid");
request.AddParameter("callback", "http://localhost"); // ????????
request.RequestFormat = DataFormat.Json;
request.AddFile("file", #"e:\MyDocuemnt.pdf");
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
The line with the parameter callback requires me to pass a url
what should I be passing in here ?
the result is passed back to the callback Url provided, how do I get to see that?
My application is a console application and I want to capture the result here.
Your API is expecting a place to dump the results after it has been processed.
This is what is happening as per my understanding.
You make a call to the API and expects you to provide a callback url
The API returns you a response.
Now the question here is where is my result and if it is sent to the callback url how do I get it.
This is waht you need to do.
You could create a Web API with a POST method that would do the trick for you.
Make sure you are hosting your WebApi which should be accessible by the service which you are calling and expect to send you the result.
public void Post([FromBody]JToken value)
{
var path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data");
File.WriteAllText(path + #"/WriteJSON" + DateTime.Now.Ticks.ToString() + ".txt", value.ToString());
// write any code that you want to here
}
This should do the trick for you.All i am doing here is writing the response back you may want to do whatever you wish to do with this.
I have an Asp.net Web API project which has several CRUD methods.
On top of these methods, i want to add an Authorization service that reads the Authorization header and prevent users of accessing the resources (if they are not authorized).
// Method on internal IP Project
public class InternalController : ApiController
{
public void Create(CreateRequest request)
{
// implement the method
}
}
// Method on public IP Project
public class ExternalController : ApiController
{
public async Task Create(CreateRequest request)
{
// validate Authorization header and throw exception if not valid
using (HttpClient client = new HttpClient())
{
string parameters = string.Format("param1={0}¶m2={1}", request.Param1, request.Param2);
client.BaseAddress = new Uri("http://192.168.1.1/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/internal/create?" + parameters);
response.EnsureSuccessStatusCode();
}
}
}
Is there any way of "Redirecting" the request from the External API to the Internal API more easily?
Right now, i have to manually re-create all the parameters that i receive in ExternalAPI and send them in the InternalAPI, even if they are the same.
Can i make HttpClient automatically send the HttpRequestMessage (Request) object that i have in ExternalAPI method?
When speaking about ASP.NET Web API. HttpClient will not automatically redirect you. When you have become response from internal service you can pass it to external. Or you can redirect your action like here
To make it correct redirection for client from REST point of view use HTTP Redirect Headers and repsonse codes. For example HTTP response code 302. And then client should be able to react on such response code and get redirect address from Location header. But it's about redirect for client.
When speaking about call of some internal services from your API from architecture. You have following alternatives:
Call your internal service as class method
Make service to service call
Setup message queue or bus and your API will communicate with it through service bus.
Call your internal service as class method
Very easy. No impact and delays for service call. But you should reference assembly and it's not always possible. Or such way could be not possible due to requirements
Make service to service call
Has disadvantages: your services are tightly coupled, you have delay and should wait for response from internal service. It's considered as bad practice. But could be a good temporarily solution as first step to service bus.
Setup message queue or bus and your API will communicate with it through service bus.
Your services are decoupled and independent. You shouldn't wait for response. But it's technically harder to set up and make your architecture and infrastructure more complex/
As summary
There is no best way from the box for your architecture and you should select from alternatives based on your requirements.
Here is the sample code to Post the data to web api:-
var handler = new HttpClientHandler {UseDefaultCredentials = true};
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("https://IE url.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var postDataObject = new
{
SCName = properties.Site.PortalName,
TotalSites = properties.Web.Webs.Count
};
var jsonPostData = new JavaScriptSerializer().Serialize(postDataObject);
HttpContent content = new StringContent(jsonPostData, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("/controllerclassname/InsertUpdateDataOperation", content).Result;
if (response.IsSuccessStatusCode)
{
//Check the response here
// var webApiResponse = response.Content.ReadAsStringAsync().Result;
}
Ok, so I have the service reference in my .NET project. And yes I know that you now have access to proxy classes.
But in the past, I am used to doing this via an HttpWebRequest object using NVP, but never tried using the WSDL and sending a SOAP request this way.
I'm not quite sure which object to use to send the request. Not sure where to start here. I've looked at the docs but seen no good examples out there for .NET and PayPal.
Other than a WSDL vs. sending an HttpWebRequest via a NVP API and querystring params, I really do not understand if there's a difference in how you send the request. It's all just over Http so can't you use HttpWebRequest also over a SOAP API (using WSDL)?
You start by generating a service reference from the metadata: Right click on the project -> Add Service Reference and point to the WSDL url: https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
This will generate proxy classes to the current project which could be used to send requests:
using (var client = new PayPalAPIInterfaceClient())
{
var credentials = new CustomSecurityHeaderType
{
Credentials = new UserIdPasswordType
{
Username = "username",
Password = "password"
}
};
var request = new AddressVerifyReq
{
AddressVerifyRequest = new AddressVerifyRequestType
{
Street = "some street",
Zip = "12345"
}
};
var response = client.AddressVerify(ref credentials, request);
}