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
Related
I am trying to queue a build from my TFS servers using the TFS Rest API nuget package for c#. However, upon sending the request to the server with the JSON:
"definition":{ "id":63 }
I get a 400 response back with the error:
message=Value cannot be null. Parameter name: build.Definition
I think I am sending the JSON correctly, considering before I was getting errors saying it couldnt be deserialized, or that there wasnt a JSON in the first place.
Can someone help me figure out what is causing this error and how to fix it?
For reference and showing what I have already used as help:
Microsoft Documentation
Queue Build using Powershell
Again Queueing a build in powershell
And several other articles (google "queue build tfs rest api c#")
//post request for queuing the build
var client = new RestClient(websiteName);
var request = new RestRequest("_apis/build/builds?ignoreWarnings=true&sourceBuildId=63&api-version=4.0", Method.POST, DataFormat.Json);
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("{\"definition\"", "{\"id\":63}}");
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalAccessToken))));
request.AddJsonBody(values);
IRestResponse response = client.Execute(request);
"definition":{ "id":63 } isn't valid JSON.
{ "definition":{ "id":63 } } is.
Don't construct JSON as a string, use ConvertTo-Json on an associative array to turn an appropriately-shaped object into JSON, such as
$body = #{
definition = #{
id = $definitionId
}
} | ConvertTo-Json -Depth 100
If you use the Rest API nuget packages, you can use build-in methods to queue a new build, this will much convenient than using HttpClient or other class:
var url = new Uri("http://tfsServer:8080/tfs/MyCollection/");
var connection = new VssConnection(url, new VssCredentials());
var buildServer = connection.GetClient<BuildHttpClient>();
// Get the list of build definitions.
var definition = buildServer.GetDefinitionAsync("teamprojectname", 33).Result;
//It requires project's GUID, so we're compelled to get GUID by API.
var res = buildServer.QueueBuildAsync(new Build
{
Definition = new DefinitionReference
{
Id = definition.Id
},
Project = definition.Project
});
Console.WriteLine($"Queued build with id: {res.Id}");
If you still want to use the URL to trigger, here is also an example:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://tfsServer:8080/tfs/DefaultCollection/TeamProject/_apis/build/builds?api-version=4.0");
request.Credentials = CredentialCache.DefaultNetworkCredentials;
request.Method = "Post";
request.ContentType = "application/json";
Stream stream = request.GetRequestStream();
string json = "{\"definition\":{\"id\":63}}";
byte[] buffer = Encoding.UTF8.GetBytes(json);
stream.Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.Write(response.StatusCode);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Console.Read();
I have a problem with the POST method. I have a REST server programmed in C#, and I want to consume this REST service in C#, but I don't know how. The problem is that my method accepts a POST, receives a JSON payload and returns an HTTPStatusCode and a number:
id_task= planificadorService.CreaTarea(tareaDTO);//tareaDTO is a JSON
if (id_tarea == 0)
{
response = Request.CreateResponse(HttpStatusCode.NotFound, "Cannot create task ");
return response;
}
response = Request.CreateResponse(HttpStatusCode.Created);
response.Content = new StringContent(JsonConvert.SerializeObject(id_task), Encoding.UTF8, "application/json");
return response;
It was easy to do it using the GET method with the WebRequest and HttpWebResponse classes, but I don't know how to do it with the POST method. After many attempts, I ended up with something like this:
public void PostTareas(Tarea tarea)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url_base + "/v1/tareas");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
string json = JsonConvert.SerializeObject(tarea);
var client = new HttpClient()
{
BaseAddress = new Uri(url_base + "/v1/tareas")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
response.Content= new StringContent(JsonConvert.SerializeObject(tarea).ToString(), Encoding.UTF8, "application/json");
response = client.PostAsync(url_base + "/v1/tareas", json)).Result;
}
I'm on the right track? How can I do this so that I am able to access the Json content? Thanks
P.D- Excuse my english, it is not my native language and I know there may be faults in expressing myself
With WebRequest you need to write the JSON in the POST request payload, use WebRequest.GetRequestStream:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url_base + "/v1/tareas");
...
using(var requestStream = request.GetRequestStream()) {
// Write the serialized json into the stream, it will be send as payload
using(TextWriter writer = new StreamWriter(requestStream)) {
writer.WriteLine(JsonConvert.Serialize(tarea));
}
}
var response = request.GetResponse();
or you can use HttpClient and call PostAsync, as you're doing in your second part of your code. Either way is fine, but stick to one :)
You should also consider using a high(er) level library, like RestSharp. Ultimately consider exposing your server API with Swagger via Swashbuckle, generate a client with swagger-codegen and spend your time at the higher level abstraction of the API, not the HTTP/Json layer.
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
I am working on a c# console application where I am making a Http Post request to a web api by using xml file and I'm kind of new to XML and web services but I figured out the following code for the request but failed to pass xml data to the method
static void Main(string[] args)
{
string desturl=#"https://xyz.abcgroup.com/abcapi/";
Program p = new Program();
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
}
public string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
For obvious reasons the above code throws 404 error as I think I am not passing the xml data properly
May I know how I can fix this?
You're not posting xml, your posting the string C:\Applications\TestService\FixmlSub.xml
Change your method call from:
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
to
var xml = XElement.Load(#"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));
If you are trying to learn post / receive, go for it. But there are open source libraries that are already well tested to use if you want to use them.
The non-free version of Servicestack.
And their older free-version. I think the older free version is great. I've never tried the newer one. You deal with objects, like say an Employee and pass that to the library and it does the translation to xml or whatever the web-service wants.
You can post whole strings if you want. They have great extension methods to help you with that too.
I have the following MVC method.
[System.Web.Mvc.HttpPost]
public ActionResult Listen(string status)
{
CFStatusMessage statusMessage = new CFStatusMessage();
if (!string.IsNullOrEmpty(status))
{
statusMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<CFStatusMessage>(status);
}
return Content(Server.HtmlEncode(status));// View(statusMessage);
}
I am trying to call the above method from Other application .. (Console). I am using HttpWebRequest to make a call to the MVC Method. Using the below code its able to call the method but the Parameter is always coming as empty string.
string content = "{\"status\":\"success\",\"payload\":\"some information\"}";
string url = "http://myrl.com";
var httpWRequest = (HttpWebRequest) WebRequest.Create(url);
httpWRequest.Method = "POST";
httpWRequest.ContentType = "text/json";
var encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(string.Format("status={0}", Uri.EscapeDataString(content)));
httpWRequest.ContentLength = data.Length;
Stream stream = httpWRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
var response = (HttpWebResponse)httpWRequest.GetResponse();
With this its making a call to Listen method but status parameter is always coming blank. whereas I want the json string {status:"success",payload:"some information"} as parameter.
What am I doing wrong?
P.S.: I tried the below statement as well, while sending the actual content.
byte[] data = encoding.GetBytes(content);
Regards,
M
If do you need to provide any kind of service from MVC tryout WebApi instead. You can use HTTP REST to do this easily.
Read more here ASP.NET WebApi
You appear to be saying the request is json, but sending it using wwwencoding.
Remove the status={0} line bit & just send the json as is.
You can try something like this
using (var sw = new StreamWriter(httpWRequest.GetRequestStream()))
{
sw.Write(content);
sw.Flush();
sw.Close();
}