C# Console Rest API header payload - c#

I need to access a Portal which is controlled with Bearer Authentication. Client needs to obtain authentication token then add it to each request
URL ~/token
Method POST
Content-Type application/x-www-form-urlencoded
Payload grant_type=password&username=UserName&password=Password
**How do i add the payload which includes the grant type and username and password to my code **
so far my code is as follows :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ConsoleRestClient
{
class Program
{
static void Main(string[] args)
{
string URI = "https://token";
WebRequest request = WebRequest.Create(URI);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
}
}`
}

You should be sending your request with content type "application/json" and put requested login variable on the body. To give you an idea:
Headers:
Content-Type:application/json
Body:
{ "username": "MyUserName", "password": "MyPassword" }

Probably you can try adding to the request headers, by doing something like this:
string URI = "https://token";
WebRequest request = WebRequest.Create(URI);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.headers.Add(<header_name>, <header_value>);
then you read these headers on your api.

Related

HttpClient and HttpWebRequest cannot make empty Post request

Seems HttpClient is not able to perform the following post request (it throws validation errors)
POST with URI encoded parameters
no Body but Content-Type header setted.
I'm sure this is a problem of usage of C# since I was able to perform the correct request with Postman (see the image)
The service I'm trying to authenticate against is this one Fitbit OAUTH2
I tried also HttpWebRequest, but I failed to do that even with that class, however here's also the second attemp. Seems C# is performing some action different from Postman but I have to figure out which action. Does anyone ever had a similiar issue?
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public static class MyRequest
{
public static string Call( string uri, string headerName, string header)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create( uri);
webRequest.Method = "POST";
webRequest.Headers.Add( "Authorization", $"{headerName} {header}");
webRequest.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse) webRequest.GetResponse();
if(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
{
}
else
{
return null;
}
using ( var stream = response.GetResponseStream())
{
return stream.ToString();
}
}
}
If I use the HttpClient with the following content
content = FormUrlEncodedContet( keyValues)
the final URL do not have the #_=_ appended, and that is requested by that service otherwise it returns 401

Web API: FromBody always null

I'm trying to develop a web API, and when I test the POST method, the body is always null. I have tried everything when sending the request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/SomeAPI");
req.Method = "post";;
var aaa = Encoding.Default.GetBytes("Test");
req.ContentType = "application/xml";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream())) {
Console.WriteLine(sr.ReadToEnd());
}
I use a breakpoint, and the API is called properly, but the body member is always null:
[HttpPost]
public void Post([FromBody]String test) {
}
try
[HttpPost]
public void SomeApi()
{
var test = HttpContext.Current.Request.Form["Test"];
}
If u send correctly the value,this will work 100%
Your Content Type is set to XML so you must pass the data as XML. This means wrapping your data in <string> element.
I would recommend using RestSharp (http://restsharp.org/) for making WebAPI calls from .Net.
var client = new RestClient("http://localhost:1748/");
var request = new RestRequest("api/SomeAPI", Method.POST);
request.AddBody("Test");
var response = client.Execute(request);
Update
I have created a sample project and it works absolutely fine:
Server side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class HomeController : ApiController
{
[Route("api/TestAPI")]
[HttpPost]
public IHttpActionResult Post([FromBody]String test)
{
return Ok(string.Format("You passed {0}.", test));
}
}
}
Client side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/TestAPI");
req.Method = "post"; ;
var aaa = Encoding.Default.GetBytes("\"Test\"");
req.ContentType = "application/json";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
}
After installing the WEB API service in IIS and running the console app it prints:
"You passed Test."
Please note the quotes around the response.
If you want to use XML then you need to modify the content type and data you are sending:
var aaa = Encoding.Default.GetBytes("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Test</string>");
The response you will get is
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You passed Test.</string>
Both samples in the debugger will have correct value passed in the test parameter.
Two things to try, 1st, try your request using a tried and tested tool like Postman. This will eliminate any chance your request is malformed in any way. 2nd, try changing your ContentType to text/plain. It's possible the request pipeline is seeing application/xml but your request body is invalid xml which really should be a bad request but is just being serialized as null.

Post request to a service, get response ,validate response

I am looking for a sample code to send request to a web service( SOAP) using C# .net
Get the response back and then validate the response automatically
Ex:http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit
Send celcius data to this web service and get some response back and then validate this response with expected values.
I am looking to do this programmatically using C# nunit framework
Does anyone have idea how to achieve this?
There should be no logic worth testing in the web service itself.
You cannot easily test the web service call, and nor should you. This is the responsibility of the Framework.
Your web service should be a wrapper around the class that does the real work. You would then unit test the class with the logic in, not the web service.
In your example, you should have a class who's responsibility it is to convert Fahrenheit to Celsius. The public method that does this would be covered by your unit tests.
The end point you call to actually perform the conversion (for example, the methods in your .asmx file) would simply call the code above.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using NUnit.Framework;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main()
{
String b = "OK";
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("your end point here");
request.Headers.Add ("SOAPAction", "some soap action here");
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = #"<s:Envelope xmlns:s="Som request that you want to send";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
int a = 0;
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Assert.AreEqual(response.StatusCode, b, "Pass");
Console.WriteLine(((HttpWebResponse)response).StatusDescription);

Fetching data behind username/password authentication

I'd like to download some data from a forum. The page containing the data is visible only to registered users. Here's an example webpage containing user data;
http://www.bikeforums.net/member.php/227664-StackOverflow
I'd like to get the data using wget or C#. I tried logging in via Firefox, then passing the cookies file (hopefully containing the login information) to wget. That was more of a makeshift hack and not a real solution, but it still failed. How do I do this properly?
I set up an account for testing if that's helpful.
User: StackOverflow
Pass: so123
Using firebug you can easily get the POST data for the login page and use it to create a WebRequest and Login to the Forum.
The Server create the cookies for authentication and we can use this cookies in the next request on the forum page so the server can authenticate the request and return all the data.
Here I've tested a simple console application that achieves this mechanism.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Web;
using System.Net;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest wpost = (HttpWebRequest) HttpWebRequest.Create("http://www.bikeforums.net/login.php?do=login");
wpost.CookieContainer = cookieContainer;
wpost.Method = "POST";
string postData = "do=login&vb_login_md5password=d93bd4ce1af6a9deccaf0ea844d6c05d&vb_login_md5password_utf=d93bd4ce1af6a9deccaf0ea844d6c05d&s=&securitytoken=guest&url=%2Fmember.php%2F227664-StackOverflow&vb_login_username=StackOverflow&vb_login_password=";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
wpost.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
wpost.ContentLength = byteArray.Length;
// Get the request stream.
System.IO.Stream dataStream = wpost.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse) wpost.GetResponse();
// Request
wpost = (HttpWebRequest)WebRequest.Create("http://www.bikeforums.net/member.php/227664-StackOverflow");
//Assing the cookies created on the server to the new request
wpost.CookieContainer = cookieContainer;
wpost.Method = "GET";
response = (HttpWebResponse)wpost.GetResponse();
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
//Display the result to console...
Console.WriteLine(readStream.ReadToEnd());
response.Close();
readStream.Close();
Console.Read();
}
}
}

How to send an HTTPS GET Request in C#

Related: how-do-i-use-webrequest-to-access-an-ssl-encrypted-site-using-https
How to send an HTTPS GET Request in C#?
Add ?var1=data1&var2=data2 to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
Simple Get Request using HttpClient Class
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("https://www.google.com").Result;
}
}
I prefer to use WebClient, it seems to handle SSL transparently:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
Some troubleshooting help here:
https://clipperhouse.com/webclient-fiddler-and-ssl/

Categories