How to do an API call in ASP.NET (VB) - asp.net

I want to make an API call where the response is in XML format.
This is the API description: http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm
I have registered and I have a key to use in the request URL.
Could anyone give me an idea of how to make the call and analyse the response?
Thankyou.

Something along the lines of:
var request = WebRequest.Create("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/hypocrite?key=1234");
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
Then you can grab what you need like:
xdoc.Element("ElementName");

Related

How to stop ASP .NET from JSONifying JSON

I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).
How can i get it so asp does not jsonify the string
You can write your json data directly to response and set right content headers.
public HttpResponseMessage GetData()
{
var json = "\"value\": \"da\\ta\"";
var resp = Request.CreateResponse(HttpStatusCode.OK);
resp.Content = new StringContent(json);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API
return resp;
}

web api (asp.net) - sending data via post method

I'm trying to pass data via post method from my client to a server.
I'm using WebApi to do so.
This i the code i used:
client:
var client = new RestClient();
client.EndPoint = #"http://localhost:57363/hello";
client.Method = HttpVerb.POST;
client.PostData = "{value: Hello}";
var json = client.MakeRequest();
Console.WriteLine(json);
Console.Read();
server:
// POST api/<controller>
public string Post([FromBody]string value)
{
return value + ", world.";
}
The server responds as expected when using postman. However, the client passes a null value instead of the real value.
What am i doing wrong?
First of all a correct json would look like "{value: 'Hello'}".
I use json-online to easily validate such inline json.
On the other hand, I think that you should send just the value in this case, not the entire json (because you are trying to resolve a simple type,a string), so the client should send a request like:
client.PostData = "'Hello'";

Get string from current URL

I am writing an asp.net MVC Application. I have the application send a request to FreeAgent and if the request is successful a code is returned in the redirect of the URL.
For example this is a copy of a successful URL.
{
http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=
}
They have added the ?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state= to my URL
I need the bit after the ?code= and before &state=
I can use this to get the URL
string code = Request.Url.AbsoluteUri;
but I need help extracting the code from this
edit:
The code will be different each time it is run
You can use the System.Uri and System.Web.HttpUtility classes
string uri = "http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=";
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
Then the value of the code query parameter will be available in queryDictionary["code"]

Invoke server side method using XMLHttpRequest

how can i directly call my own server side function using XMLHttpRequest.
suppose i have one static webmethod in my aspx file then how can i call it by XMLHttpRequest. what header info i need to pass to asp.net engine and as a result asp.net engine can invoke my method and return the response back in the out going stream.
this way i need to call my server side method
<script type="text/javascript">
var request;
// A
// Here is the new function that is called when the user submits the form.
// This example uses POST.
function submitCallback() {
var inputValue = document.getElementById("SearchInput").value;
var sendStr = "name=" + inputValue;
request = new XMLHttpRequest();
// B
// Specify the POST method and send it.
request.open("POST", "Default.aspx/Getdata");
request.onreadystatechange = readyCallback;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("IsLookup", "true");
request.send(sendStr);
}
</script>
please guide me....thanks
I believe you are probably referring to ASP.NET Page Methods when you say One static webmethod in my aspx file. ASP.NET page methods (or web services for consumption in JS) uses JSON serialization for i/p and o/p. So you need to set JSON as the content type for the request and actually send the JSON string in the body i.e.
...
var sendStr = "{name:" + inputValue + "}";
...
request.setRequestHeader("Content-Type", "application/json");
...
request.send(sendStr);
Further, I will suggest you to use jquery or ASP.NET generated proxies (by ScriptManager) instead of directly coding against XmlHttpRequest. See this article for how to use jquery for calling Page methods.
I think, the easiest way will be usage of jQuery for ajax requests: http://api.jquery.com/category/ajax/

WCF Service Call during post

I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/

Resources