FromBody string input not binding in REST web service - c#

I am trying test out a REST service implemented as follows:
public bool loadData(string file, string page, string mapping, [FromBody]string value)
{
// Implementation
}
The code I am using to invoke this service:
uri = "http://localhost:9576/API/DataLoaderService?file=F&page=P&mapping=M";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = Method.ToUpper();
byte[] buffer = Encoding.ASCII.GetBytes("TEST_STRING");
req.ContentLength = buffer.Length;
req.ContentType = "application/x-www-form-urlencoded";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
However the "TEST_STRING" does not get bound to the [FromBody]string value.

As you can see in this my previous question (little different from yours) when you use [FromBody] you should use = and then the value of the parameter.
So in your case try
byte[] buffer = Encoding.ASCII.GetBytes("=TEST_STRING");
instead of
byte[] buffer = Encoding.ASCII.GetBytes("TEST_STRING");

Related

how to make POST request in C#

im trying to create a post request to collect date from web site
my request should be like this :
POST /api/recent HTTP/1.1
Host: domain.org
Content-Type:application/x-www-form-urlencoded
api_token=YOUR_TOKEN_VALUE
i trying this 0 error but is not working :
private const string URL = " MY url";
private const string Parameters = "api_key= my key";
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
Try to create your POST requests using RestSharp
Source code and some tutorials available on GitHub, tons of questions here on SO

The stream does not allows seek operations. What are possible solutions?

public static string MakePOSTWebREquest(string url, string contentType, string postData)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
if (!String.IsNullOrEmpty(contentType))
{
req.ContentType = contentType;
}
else
{
req.ContentType = "application/x-www-form-urlencoded";
}
req.Method = "POST";
byte[] pbytes = Encoding.UTF8.GetBytes("list=");
byte[] arr = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = arr.Length + pbytes.Length;
Stream stream = req.GetRequestStream(); //error stream does not allows seek operation
stream.Write(pbytes, 0, pbytes.Length);
stream.Write(arr, 0, arr.Length);
stream.Close();
HttpWebResponse webResp = (HttpWebResponse)req.GetResponse();
//Now, we read the response (the string), and output it.
Stream respStream = webResp.GetResponseStream();
GZipStream zStream = new GZipStream(respStream, CompressionMode.Decompress);
StreamReader reader = new StreamReader(zStream);
string respData = reader.ReadToEnd();
return respData;
}
I am getting an exception that says
This stream does not supports seek operation.
What are the possible solutions? This code runs for some time and after some time it gives a error message of The operation has timed out.

post data through httpwebrequest and get it in php

I have this php code in server :
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
and i am sending post data by httpwebrequest in c# :
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") 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());
}
static html codes of php page are shown.
but nothing of posted value are shown in messagebox .that means no data are posted.
what is wrong?
You need to get the bytes of the data.
Try this code, from this guy's blog post.
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}

Post and read binary data in ASP.NET MVC

I have a problem with posting of binary data to server via HttpWebRequest. Here is my client code:
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.UserAgent = RequestUserAgent;
request.ContentType = "application/x-www-form-urlencoded";
var responseStr = "";
var dataStr = Convert.ToBase64String(data);
var postData = Encoding.UTF8.GetBytes(
string.Format("uploadid={0}&chunknum={1}&data={2}", uploadId, chunkNum, dataStr));
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
dataStream.Close();
}
And then I want to work with request via MVC controller, here is it's signature:
public ActionResult UploadChunk(Guid? uploadID, int? chunkNum, byte[] data)
But I have error here, saying that data is not Base64 coded array, what am I doing wrong?
You need to escape the + characters in your Base64 by calling Uri.EscapeDataString.

Sending File in Chunks to HttpHandler

I'm trying to send a file in chunks to an HttpHandler but when I receive the request in the HttpContext, the inputStream is empty.
So a: while sending I'm not sure if my HttpWebRequest is valid
and b: while receiving I'm not sure how to retrieve the stream in the HttpContext
Any help greatly appreciated!
This how I make my request from client code:
private void Post(byte[] bytes)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2977/Upload");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.SendChunked = true;
req.Timeout = 400000;
req.ContentLength = bytes.Length;
req.KeepAlive = true;
using (Stream s = req.GetRequestStream())
{
s.Write(bytes, 0, bytes.Length);
s.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
}
this is how I handle the request in the HttpHandler:
public void ProcessRequest(HttpContext context)
{
Stream chunk = context.Request.InputStream; //it's empty!
FileStream output = new FileStream("C:\\Temp\\myTempFile.tmp", FileMode.Append);
//simple method to append each chunk to the temp file
CopyStream(chunk, output);
}
I suspect it might be confusing that you are uploading it as form-encoded. but that isn't what you are sending (unless you're glossing over something). Is that MIME type really correct?
How big is the data? Do you need chunked upload? Some servers might not like this in a single request; I'd be tempted to use multiple simple requests via WebClient.UploadData.
i was trying the same idea and was successfull in sending file through Post httpwebrequest. Please see the following code sample
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName +
"&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}
I have blogged about it, you see the whole HttpHandler/HttpWebRequest post here
http://aspilham.blogspot.com/2011/03/file-uploading-in-chunks-using.html
I hope this will help

Categories