Web API2 read request body - vb.net

I have a web API2 item that I need to read the 'body' of the incoming request. The client is sending information (via 'PUT') in the body opposed to parameters in the URL. I have been searching for a solution but keep hitting a wall. Can anyone advise how I can get this body text?
Thanks
<HttpOptions>
<Route("v1/cth/test"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterface(ByVal passedjson As Object) As String
Return "Hello"
End Function

FYI, I finally managed to get to the body. Hope this helps someone else.
<HttpOptions>
<Route("v1/cth/dev"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterfaceDev() As String
Dim CTHStream As New StreamReader(HttpContext.Current.Request.InputStream)
Dim CTHBody As String = CTHStream.ReadToEnd
Return "Hello"
End Function

Related

How to get data from API by using post method in Roku?

I want to get data from API in Roku by passing parameter in body using post method if any one have any idea please late me know.
Thank you!
You can use the roURLTransfer's postFromString() method to do a post request. Just make sure to set the Content-Type header first so the server knows how to interpret the post body.
I haven't tested this, but it should get the general point across.
' Set a movie as a favorite
function markMovieAsFavorite(movieId as integer, isFavorite as boolean)
body = {
movieId: movieId
isFavorite: isFavorite
}
'create the request
request = createObject("roUrlTransfer")
'set the HTTP method. can be "GET", "POST", "PUT", etc...
request.setRequest("POST")
'assign the headers to the request,
request.setHeaders({
'set the content-type header
"Content-Type": "application/json"
})
'run the request
responseCode = request.postFromString(formatJson(body))
'check the response code to make sure it's ok.
return responseCode = 200
end function
You could also consider using a library like roku-requests which does most of this for you out of the box.

Can somebody give me an example of getting the content of a page from a URL in vb.net for windows 8?

I am very new to vb/.net and I'm trying to do something that I can do easily in classic vb. I want to get the source html for a webpage from the URL.
I'm using vb.net in Visual Studio Express for Windows 8.
I've read loads of stuff that talk about HttpWebRequest, but I can't get it to work properly.
I did at one point have it returning the html header, but I want to content of the page. Now, I can't even get it back to giving me the header. Ultimately, I want to process the html returned which I'll do (to begin with) the old-fashioned way and process the returned html as a string, but for now I'd like to just get the page.
The code I've got is:
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(New Uri(URL))
txtHTML.Text = request.GetRequestStreamAsync().ToString()
Can anyone help me with an example to get me going please?
You're trying to use an Async method in a synchronous way, which won't make any sense. If you're using .NET 4.5, you can try marking the calling method with Async and then using the Await keyword when calling GetRequestStreamAsync.
Public Sub MyDownloaderMethod()
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest
= System.Net.HttpWebRequest.Create(New Uri(URL))
' Use the Await keyword wait for the async task to complete.
Dim response = request.GetResponseAsync()
txtHTML.Text = response.GetResponseStream().ToString()
End Function
See the following MSDN article for more information on async programming with the Await keyword: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
Edit
You are receiving your error because you're trying to get the Request stream (what you send the server), and what you really want is the Response stream (what the server sends back to you). I've updated my code to get the WebResponse from your WebRequest and then retrieve the stream from that.
Public Shared Function GetWebPageString(ByVal address As Uri) As String
Using client As New Net.WebClient()
Return client.DownloadString(address)
End Using
End Function
There is also DownloadStringAsync if you don't want to block
request.GetRequestStreamAsync() is probably not a method. I think you're cribbing code from a site where someone wrote their own add-on methods to HttpWebRequest. Try request.GetResponse() to return a response object, then in the response object you can inspect the stream and convert it to text if you need to.
This worked for me in VB.Net 4.5
Public Async Sub GetHTML()
Dim PageHTML as string
Dim client As New HttpClient
Dim getStringTask As Task(Of String) = client.GetStringAsync(PageURL)
PageHTML = Await getStringTask
MsgBox(PageHTML)
End Sub

Windows Phone VB Web Request

does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun

Send a POST request to one page but redirect to another

Really having trouble trying to implement this in my controller. Essentially as it stands I have a controller than when it completes passes the user to a URL as below:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
However I am trying to implement the functionality to send an SMS each time this controller is called and have got this working with a URL like (made up without username or password):
http://go.bulksms.com:1557/send?username=fred&message=hello
This needs to be accessed via an HTTP post request. I understand I can return this URL in the 'Return Redirect' above but I want both to happen (the redirect and the post on this link sending the SMS) and ideally I want the user to be redirected to the page as it happens now but the SMS to be sent in the background. How would I implement this?
Try this. New code is added between two comment line. You can also consult this url for details, if it's a POST you might have to pass some form data, it's all described in the link above.:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
'Sending SMS here: (start)
Dim request as WebRequest = WebRequest.Create("http://go.bulksms.com:1557/send?username=fred&message=hello")
request.Method = "POST"
Dim response As WebResponse = request.GetResponse()
'end
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
Redirect is always a GET request
for posting to the different URL , You need to call it from your code using HttpWebRequest class.

Passing a string param to a RESTful service during POST action

I am having a RESTful service with the following method:
[WebInvoke]
string GetDataFromStringAsString(string xmlString);
My client call to the method is as below:
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method){RequestFormat = DataFormat.Xml};
request.Resource = resourceUrl;
request.AddParameter("text/xml", requestBody,
ParameterType.RequestBody);
var response = client.Execute(request);
Let us take a string to post as "Hello World".
Now the string that i post to the above method gives me a 400 Bad
request. In order to get it working i had to wrap the above string in
a element as shown below:
<string xmlns="http://schemas.microsoft.com/2003/10/
Serialization/">Hello World</string>
Now when i post the above string i get a success response back from
the server.
Why is that i have to manually wrap the string to make it work. Is
there a way that i can achieve to post a string without doing the
above manually.
The only other way that I am aware of is to use stream as your input parameter. e.g.
[WebInvoke]
string GetDataFromStringAsString(stream xmlString);
The problem with .Net 4 WCF REST is that fundamentally WCF only knows how to pass two types of info, either XML or a stream of bytes. Personally, I would use WCF Web API instead of the standard WCF REST library because you are going run into lots more of these kinds of issues.