Posting data from winforms to mvc controller passes null value - winforms

I am trying to post a string value from winforms (which is a ClickOnce application) to MVC controller action method. Am able to successfully call the POST method, but on checking the parameter value it shows as null value.
Following is my winform code:
private void btnEncrypt_Click(object sender, EventArgs e)
{
var dataBytes = System.Text.Encoding.UTF8.GetBytes(txtFill.Text);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://abc.azurewebsites.net/Home/Contact");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = dataBytes.Length;
httpWebRequest.Method = "POST";
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(dataBytes, 0, dataBytes.Length);
dataStream.Flush();
dataStream.Close();
WebResponse response = httpWebRequest.GetResponse();
lblShow.Text = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(dataStream);
string responseFromServer = streamReader.ReadToEnd();
// Display the content.
lblShow.Text += " " + responseFromServer;
streamReader.Close();
response.Close();
}
Following is the screenshot from my controller action method where the breakpoint gets hit, but parameter post value is null.
Any approach / suggestions on what is going wrong or how to pass a string or JSON values from winforms to my mcv controller action.
Thanks In Advance!!!..

try this :
private void btnEncrypt_Click(object sender, EventArgs e)
{
var dataBytes = System.Text.Encoding.UTF8.GetBytes("data="+txtFill.Text);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://abc.azurewebsites.net/Home/Contact");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = dataBytes.Length;
httpWebRequest.Method = "POST";
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(dataBytes, 0, dataBytes.Length);
dataStream.Flush();
dataStream.Close();
WebResponse response = httpWebRequest.GetResponse();
lblShow.Text = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(dataStream);
string responseFromServer = streamReader.ReadToEnd();
// Display the content.
lblShow.Text += " " + responseFromServer;
streamReader.Close();
response.Close();
}

Related

HttpWebRequest in Silverlight

How to recreate the following code in Silverlight? I'm pretty lost when it comes to async.
public class StringGet
{
public static string GetPageAsString(Uri address)
{
string result = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
return result;
}
public void DownloadHtml(Uri address){
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += WebClientDownloadString_Complete;
webClient.DownloadStringAsync(address)
}
private void WebClientDownloadString_Complete(object sender, DownloadStringCompletedEventArgs e) {
if (e.Error == null) {
string html = e.Result;
}
}

WebClient.UploadStringAsync does not POST data to the server correctly

I am trying to post an email address and password to a server in order to receive JSON back. However the following code receives a response from the server indicating that the POST data was not received.
private void BtnSignIn_Click(object sender, RoutedEventArgs e)
{
String email = Email.Text;
String password = Password.Password;
String data = "email=" + email + "&password=" + password;
WebClient wc = new WebClient();
Uri uri = new Uri("http://api.server.com/login");
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(uri, "POST", data);
}
The string data is produced correctly in the format email=test#test.com&password=hunter2.
And the event handler function...
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
What do I need to do to ensure the fields are posted to the server correctly? Thanks!
You need to add wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; and
wc.Encoding = Encoding.UTF8; in your code. This will post your data to server correctly.
See below code this will help u...
private void BtnSignIn_Click(object sender, RoutedEventArgs e)
{
String email = Email.Text;
String password = Password.Password;
String data = "email=" + email + "&password=" + password;
WebClient wc = new WebClient();
Uri uri = new Uri("http://api.server.com/login");
wc.UploadStringCompleted += new ploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
wc.UploadStringAsync(uri, "POST", data);
}

HttpWebRequest "POST" returning server error (Exception)

I'm trying to call the google URL shortner API from a WP7 app, I tried first on a Console Application by doing this:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"longUrl\":\"http://www.google.com/\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
Console.Read();
and it worked fine, and returned everything OK, but when I try to do it on a Windows Phone App like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
testConnection();
}
private void testConnection()
{
if (!NetworkInterface.GetIsNetworkAvailable())
MessageBox.Show("There's no internet connection, please reconnect to the internet and try again");
else
{
var req = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
req.ContentType = "application/json";
req.Method = "POST";
req.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), req);
textBlock2.Text = "Done";
}
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data:
string postData = "http://www.google.com";
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
textBlock1.Text= streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
}
}
The code always goes to the catch of the try method and gives "not found" error.
There is a known issue with SSL and not-trusted certificates. Connection to a web site with SSL that require ClientCertificates is not supported in the current Windows Phone 7 application model (Only BasicAuthentication is supported). You can read about the same problem here: http://forums.create.msdn.com/forums/p/65076/398730.aspx
I had a similar issue (which makes sense since I started out with this code as my example...) and when I changed the following code it started working to the point where I could progress forward again.
... from:
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
... to (the equivalent of):
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

HttpWebRequest on Wp7 AsyncWaitHandle has System.NotSupportedException

I'm having trouble with a basic HttpWebRequest in a WP7 application. As soon as I call BeginGetRequestStream, it starts to go wrong. The callback method then receives an IAsyncResult with no AsyncWaitHandle.
AsyncWaitHandle = 'ar.AsyncWaitHandle' threw an exception of type 'System.NotSupportedException'
I've created a sample below that produces the error. To create this I have just taken the sample pivot application and attempted to post some data to a server in the constructor of the MainViewModel.
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
HttpWebRequest webRequest = WebRequest.CreateHttp("http://www.google.co.uk");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(BeginGetRequestStreamCallBack, webRequest);
}
private void BeginGetRequestStreamCallBack(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest) ar.AsyncState;
Stream requestStream = webRequest.EndGetRequestStream(ar);
using(StreamWriter sw = new StreamWriter(requestStream))
{
sw.Write("{ test: \"test\" }");
}
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetResponseCallback(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
WebResponse webResponse = webRequest.EndGetResponse(ar);
Stream responseStream = webResponse.GetResponseStream();
string whatCameBack = new StreamReader(responseStream).ReadToEnd();
}
Any help would as always, be greatly appreciated.
I've looked into this a little deeper, I just can't seem to POST data using BeginGetRequestStream.
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
HttpWebRequest webRequest = WebRequest.CreateHttp("http://www.google.co.uk");
//webRequest.Method = "POST";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.BeginGetRequestStream(BeginGetRequestStreamCallBack, webRequest);
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetRequestStreamCallBack(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest) ar.AsyncState;
Stream requestStream = webRequest.EndGetRequestStream(ar);
using(StreamWriter sw = new StreamWriter(requestStream))
{
sw.Write("{ test: \"test\" }");
}
webRequest.BeginGetResponse(BeginGetResponseCallback, webRequest);
}
private void BeginGetResponseCallback(IAsyncResult ar)
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
WebResponse webResponse = webRequest.EndGetResponse(ar);
Stream responseStream = webResponse.GetResponseStream();
string whatCameBack = new StreamReader(responseStream).ReadToEnd();
}
This works okay, but it is not what I want.
Any ideas?
I was being a naughty boy and not Closing the stream correctly.
using(Stream requestStream = webRequest.EndGetRequestStream(ar))
{}
All is well.

HttpWebRequest.EndGetResponse throws a NotSupportedException in Windows Phone 7

in a Silverlight-Windows Phone 7-project I am creating an HttpWebRequest, get the RequestStream, write something into the Stream and try to get the response, but I always get a NotSupportedException:
"System.Net.Browser.OHWRAsyncResult.AsyncWaitHandle threw an exception of type 'System.NotSupportedException'
My production code is far more complicated, but I can narrow it down to this small piece of code:
public class HttpUploadHelper
{
private HttpWebRequest request;
private RequestState state = new RequestState();
public HttpUploadHelper(string url)
{
this.request = WebRequest.Create(url) as HttpWebRequest;
state.Request = request;
}
public void Execute()
{
request.Method = "POST";
this.request.BeginGetRequestStream(
new AsyncCallback(BeginRequest), state);
}
private void BeginRequest(IAsyncResult ar)
{
Stream stream = state.Request.EndGetRequestStream(ar);
state.Request.BeginGetResponse(
new AsyncCallback(BeginResponse), state);
}
private void BeginResponse(IAsyncResult ar)
{
// BOOM: NotSupportedException was unhandled;
// {System.Net.Browser.OHWRAsyncResult}
// AsyncWaitHandle = 'ar.AsyncWaitHandle' threw an
// exception of type 'System.NotSupportedException'
HttpWebResponse response = state.Request.EndGetResponse(ar) as HttpWebResponse;
Debug.WriteLine(response.StatusCode);
}
}
public class RequestState
{
public WebRequest Request;
}
}
Does anybody know what is wrong with this code?
The NotSupportedException can be thrown when the request stream isn't closed before the call to EndGetResponse. The WebRequest stream is still open and sending data to the server when you're attempting to get the response. Since stream implements the IDisposable interface, a simple solution is to wrap your code using the request stream in a using block:
private void BeginRequest(IAsyncResult ar)
{
using (Stream stream = request.EndGetRequestStream(ar))
{
//write to stream in here.
}
state.Request.BeginGetResponse(
new AsyncCallback(BeginResponse), state);
}
The using block will ensure that the stream is closed before you attempt to get the response from the web server.
The issue is with how you're dealing with the accessing the original requests in the callback from BeginGetResponse.
Rather than holding a reference ot the state, get a reference back to the original request with:
var request = (HttpWebRequest)asynchronousResult.AsyncState;
Have a look at this very basic (but working) example of implementing logging in by posting email and password credentials to a website.
public static string Email;
public static string Password;
private void LoginClick(object sender, RoutedEventArgs e)
{
Email = enteredEmailAddress.Text.Trim().ToLower();
Password = enteredPassword.Password;
var request = (HttpWebRequest)WebRequest.Create(App.Config.ServerUris.Login);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetRequestStream(ReadCallback, request);
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var postStream = request.EndGetRequestStream(asynchronousResult))
{
using (var memStream = new MemoryStream())
{
var content = string.Format("Password={0}&Email={1}",
HttpUtility.UrlEncode(Password),
HttpUtility.UrlEncode(Email));
var bytes = System.Text.Encoding.UTF8.GetBytes(content);
memStream.Write(bytes, 0, bytes.Length);
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
postStream.Write(tempBuffer, 0, tempBuffer.Length);
}
}
request.BeginGetResponse(ResponseCallback, request);
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
{
using (var streamResponse = resp.GetResponseStream())
{
using (var streamRead = new StreamReader(streamResponse))
{
string responseString = streamRead.ReadToEnd();
// do something with responseString to check if login was successful
}
}
}
}
NotSupportedException can also be thrown when string url is too long. I had messed up and attached post data to url instead of post body. When the data was short, it worked just fine, but once it grew too large - EndGetResponse crashed.
Change this:
state.Request.BeginGetResponse(
new AsyncCallback(BeginResponse), state);
To this:
state.Request.BeginGetResponse(BeginResponse, state);

Resources