How to get the content of a POST request? - c#

I have a POST method in Web api that returns byte[].
[HttpPost]
[ActionName("adduser")]
public byte[] AddUser([NakedBody] byte[] data) { ... }
I make a reuest from mvc application to this method.
[HttpPost]
public ActionResult AddUser(RegistrationData data)
{
byte[] requestPcmsMessage = CryptographyHelper.GetPcmsMessageFromModel(data);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:10189/portal/adduser");
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = requestPcmsMessage.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestPcmsMessage, 0, requestPcmsMessage.Length);
}
HttpStatusCode statusCode;
string responseString = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
var responsePcmsMessage = CryptographyHelper.cryptoObject.ToBytes(responseString);
...
return View();
}
But the response I get in responsePcmsMessage is not the bytes I sent from server. So how can I get them?

I am not sure if this would be helpful but I see this website has mostly all the sample codes. They all have code attached to it at the end which is to do with getting back the response. So maybe you can try implementing it in similar manner?
Check some of the sample codes for Email Verification API. I really hope that helps you atleast a little.

public ActionResult AddUser([FromBody] RegistrationData data)

this is how I used it, using RestClient, i don't know if that works for you
// URL
string URL = "http://localhost:10189/portal/";
// client URL
var client = new RestClient(URL);
// what you want to do
var request = new RestRequest("adduser", Method.POST);
//Login-Data - if necessary
client.Authenticator = new HttpBasicAuthenticator("user", "password");
// the response you are looking for
IRestResponse response = client.Execute(request);
// return it to you
return response.Content;

Related

Getting null in httpResponseMessage when calling REST API using HTTPClient

I am trying to execute a REST API which uses HTTP POST. The API consumes and produces xml content. I am getting null in httpResponseMessage and no exception is thrown. I tried executing the same REST API through HttpWebRequest I am getting the response Below you can find Working and Not Working case. Performance wise HttpWebRequest or HTTPClient which is better ?
Not Working case HTTPClient
try {
using(var client = new HttpClient()) {
Console.WriteLine(inputxml);
var httpContent = new StringContent(inputxml, Encoding.UTF8, "application/xml");
Uri testUri = new Uri("http://127.0.0.1:8080/rest/services/getDocument");
var httpResponseMessage = await client.PostAsync(testUri, httpContent);
Console.WriteLine(httpResponseMessage.Content.ReadAsStringAsync());
if (httpResponseMessage.StatusCode == HttpStatusCode.OK) {
var messageContents = await httpResponseMessage.Content.ReadAsStringAsync();
}
}
}
Working Case HTTPWebREquest
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://127.0.0.1:8080/rest/services/getDocument");
byte[] bytes = Encoding.UTF8.GetBytes(inputxml.ToString());
request.ContentType = "application/xml";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine("responseStr " + responseStr);
return responseStr;
}
return null;
}
Here:
Console.WriteLine(httpResponseMessage.Content.ReadAsStringAsync());
You're reading the response body, and printing System.Threading.Task1` to the console. Then the next time you try to read the response body again, its stream is at its end and won't return anything.
Read the content once, await the call and store the result in a variable.
You can use RestSharp for sending HTTP Requests.
For me, the best and the simplest method for HTTP Communication.
public string SendRequest(String xml)
{
string responseMessage= "";
RestClient restClient;
restClient = new RestClient("http://127.0.0.1:8080/rest/services/getDocument");
RestRequest restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Accept", "application/xml");
restRequest.AddHeader("Content-Type", "application/xml");
restRequest.AddXmlBody(xml);
IRestResponse restResponse = restClient.Execute(restRequest);
if (restResponse.StatusCode == HttpStatusCode.OK)
{
responseMessage= restResponse.Content;
}
return responseMessage;
}
}

How to post and receive a file with web api

I have a Api Post method that I want to be able to accept any file type and that looks like this:
[HttpPost]
public async Task<IHttpActionResult> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents.Count != 1)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
"You must include exactly one file per request."));
}
var file = provider.Contents[0];
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
}
This works in fiddler when I try to post an image to it. However, I'm writing a client library and I have a method that looks like this:
public string PostAttachment(byte[] data, Uri endpoint, string contentType)
{
var request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = data.Length;
var stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
var response = (HttpWebResponse) request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
Whenever I try to post an image using this, I'm getting a UnsuportedMediaType error. I'm assuming it's because my image isn't Multi Part Content? Is there an easy way to make my request of the correct type?
If I have to change my web api post method, is there an easy way of doing that without writing files to the server and keeping it in memory?
The MultipartFormDataContent from the System.Net.Http namespace will allow you to post multipart form data.
private async Task<string> PostAttachment(byte[] data, Uri url, string contentType)
{
HttpContent content = new ByteArrayContent(data);
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
using (var form = new MultipartFormDataContent())
{
form.Add(content);
using(var client = new HttpClient())
{
var response = await client.PostAsync(url, form);
return await response.Content.ReadAsStringAsync();
}
}
}

Redirect to Url after Post data using HttpWebRequest c#

I'm integrating CashU Payment gateway.
I need to Post some data using POST method. then I want to redirect to payment gateway site.
I have done so far
[HttpPost]
public ActionResult Index(string getAmount)
{
// some more process
var getResponce = ExecutePost(getTokenCode);
}
private string ExecutePost(string tokenCode)
{
var cashuLink = ConfigurationManager.AppSettings["CashULink"].ToString();
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(cashuLink);
var postData = "Transaction_Code="+tokenCode;
postData += "&test_mode=1";
var data = Encoding.ASCII.GetBytes(postData);
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = data.Length;
using (var stream = webReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)webReq.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
My ExecutePost method is returing a Html page string in string formate. But I want to redirect on payment gateway site.
you can use
return Redirect("URl");
to redirect to a different url

Handling http response codes in GetStringAsync

i'm very new to C#, let alone Windows Phone development :)
I'm trying to send a request, get the JSON response, but if there is an error (such as 401), be able to tell the user such. Here is my code:
async Task<string> AccessTheWebAsync()
{
//builds the credentials for the web request
var credentials = new NetworkCredential(globalvars.username, globalvars.password);
var handler = new HttpClientHandler { Credentials = credentials };
//calls the web request, stores and returns JSON content
HttpClient client = new HttpClient(handler);
Task<string> getStringTask = client.GetStringAsync("https://www.bla.com/content");
String urlContents = await getStringTask;
return urlContents;
}
I know it must be something I'm doing wrong in the way that I send the request and store the response...but i'm just not sure what.
If there is an error, I get a general:
net_http_message_not_success_statuscode
Thank you!
You could use te GetAsync() method instead of the GetStringAsync().
HttpResponseMessage response = await client.GetAsync("https://www.bla.com/content");
if(!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
do something...
}
}
String urlContents = await response.Content.ReadAsStringAsync();
This way you can make use of the HttpStatusCode enumerable to check the returned status code.
Instead of using an HttpClient use a plain good old HttpWebRequest :)
async Task<string> AccessTheWebAsync()
{
HttpWebRequest req = WebRequest.CreateHttp("http://example.com/nodocument.html");
req.Method = "GET";
req.Timeout = 10000;
req.KeepAlive = true;
string content = null;
HttpStatusCode code = HttpStatusCode.OK;
try
{
using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = await sr.ReadToEndAsync();
code = response.StatusCode;
}
}
catch (WebException ex)
{
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = sr.ReadToEnd();
code = response.StatusCode;
}
}
//Here you have now content and code.
return content;
}

WP7 Create helper class for easy use HttpWebRequest with POST method

Actually I have something like this:
private void createHttpRequest()
{
System.Uri myUri = new System.Uri("..url..");
HttpWebRequest myHttpRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myHttpRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
string hash = HashHelper.createStringHash("123", "TEST", "0216");
// Create the post data
byte[] byteArray = createByteArrayFromHash(hash);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
ApiResponse apiResponse = (ApiResponse)JsonConvert.DeserializeObject<ApiResponse>(result);
}
}
It's good, it's working but now I must use these methods in every page and just change method createByteArrayFromHash which creates request. What if I want to create helper class that can help me to do this in something about 3 lines of code in page. How would you do that? I was thinking about this way but how to add request before response? Or would you do it another way? Thanks
Yeah, it's better to use async and await. Here is an example of such a wrapper:
public async Task<string> SendRequestGetResponse(string postData, CookieContainer cookiesContainer = null)
{
var postRequest = (HttpWebRequest)WebRequest.Create(Constants.WebServiceUrl);
postRequest.ContentType = "Your content-type";
postRequest.Method = "POST";
postRequest.CookieContainer = new CookieContainer();
postRequest.CookieContainer = App.Session.Cookies;
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes(postData);
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
// Can use cookies if you need
if (cookiesContainer == null)
{
if (!string.IsNullOrEmpty(postResponse.Headers["YourCookieHere"]))
{
var cookiesCollection = postResponse.Cookies;
// App.Session is a global object to store cookies and etc.
App.Session.Cookies.Add(new Uri(Constants.WebServiceUrl), cookiesCollection);
}
}
string response = await postStreamReader.ReadToEndAsync();
return response;
}
return null;
}
You can modify it as you wish

Categories