jlrolin
jlrolin

Reputation: 1614

POST NameValueCollection to Web API using WebClient.UploadValues for .NET 3.5

I have created a Web API that serves up PDF documents. I have a 4.5/4.0 client, a Javascript-only client, and I'm now attempting to create a .NET 3.5 client for a few older websites that we have. I understand that I could NUGET a few of the libraries, but from my understanding... HttpClient only works in 4.0 right now?

In any case, I'd like to use WebClient as a means to getting this done. Currently I have:

Dim js As New Script.Serialization.JavaScriptSerializer
Dim client As New Net.WebClient
client.Headers(Net.HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
Dim serializedData As String = js.Serialize(Me.PDFReport)
Dim collection As New NameValueCollection
collection.Add("value", serializedData)
Dim response As Byte() = client.UploadValues("http://www.mywebsite.com/api/report/Post/", collection)

I'm shoving my serialized data into a NameValueCollection so that I can return a Byte array with the PDF in it. I can't seem to get it to show up on the Web API side:

Public Function Post(str As NameValueCollection) As Byte()
    Dim js As New JavaScriptSerializer
    Dim obj As PDFReport = js.Deserialize(Of PDFReport)(str("value"))
    Dim rpt As New ReportService(obj)
    'Return Nothing (Commented for now until I figure out how to get values)
End Function

What am I doing wrong? I can't seem to get the values over the wire unless I use UploadString, but then I can't grab a response that is appropriate.

Upvotes: 1

Views: 2446

Answers (1)

Kiran
Kiran

Reputation: 57979

try modifying your action parameter to be FormDataCollection and see if it works. And also have this kind of check (change it to VB) to catch any model state errors.

if (!ModelState.IsValid)
{
  throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}

Upvotes: 2

Related Questions