Have a WebAPI Controller send an http request to another REST service - c#

I'm creating WebAPI service, and I want it to redirect all incoming requests (GET,POST) to an external REST service and return the response (Json/html) to the original request to my WebAPI.
What is the best way to go about doing this? HttpResponseMessage or HttpWebResponse
[HttpGet]
[Route("api/Geocoder")]
public HttpWebResponse GetCandidates(string query)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://externalRestService.com/arcgis/rest/services/Geocode" + query);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
I also tried
[HttpGet]
public HttpResponseMessage Get()
{
try
{
HttpClient httpClient = new HttpClient()
{
BaseAddress = new Uri(""https://externalRestService.com/arcgis/rest/services/Geocode")
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = httpClient.GetAsync(requestUrl).Result;
return response;
}
catch
{
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.InternalServerError,
ReasonPhrase = "Internal Server Error"
};
}
}
Thanks in advance for any help. I'm newbie at .Net Core and webapis

The following approach worked for me.
public async Task<IHttpActionResult> GET(string query)
{
string _apiUrl = "http://foo.com/rest/services/Geocode?";
string _baseAddress = "http://foo.com/rest/services/Geocode?";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.GetAsync(_apiUrl + query);
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}

Related

How to send a post request in dotnet with a list of request headers

public static async Task<HttpResponseMessage> Post(string endPoint, string data){
HttpContent c = new StringContent(data, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(VodapayBaseUrl + endPoint),
Content = c,
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = await client.SendAsync(request).ConfigureAwait(false); // The code fails here
if (result.IsSuccessStatusCode)
{
Console.WriteLine("got here");
return result;
}
else
{
Console.WriteLine("failled");
return result;
}
}
// return result;
}
Here is an updated version:
public static async Task Post()
{
using (var httpClient = new HttpClient())
{
var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";
httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Successful");
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Not successful");
}
}
}
class Program
{
private static void Main(string[] args)
{
Post().Wait();
Console.WriteLine();
}
}
}
Can someone please help with this I am new to c# and relatively new to coding. I am trying to send a request using httpclient I need to send data in a json format I also need to send a list of headers. How can I do this and also return json data at the end your help will be appreciated.I am getting an error when i run this:
Your code isn't far off, here's an example that I had in one of my projects ...
using (var httpClient = new HttpClient())
{
var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";
// Setup the HttpClient and make the call and get the relevant data.
httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Successful");
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Not successful");
}
}
... obviously, it has varying degrees of thought for the scenario at hand but just adapt it as need be.

Bad Request error setting header in Ebay API

I would like to ask help how can I fix the issue in the header of my httpclient request.
This is ebay restful api in creating a fulfillment shipment. I am able to create in Postman but when I tried it in VS, it won't work with error bad request. Screenshot below using postman.
Codes below in ASP.NET
private HttpClient CreateHttpClient()
{
var client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string baseAddress = WebApiBaseAddress;
client.Timeout = new TimeSpan(0, 5, 59);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
return client;
}
public HttpResponseMessage PostHttpResponse(string requestUri, object data)
{
var stringPayload = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.Add("Content-Language", "en-US");
using (var client = CreateHttpClient())
{
try
{
HttpResponseMessage response = client.PostAsJsonAsync(requestUri, httpContent).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
GetErrorsResponse(response);
throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
}
}
catch (HttpRequestException ex)
{
throw ex;
//return null;
}
}
}
I was able to fix the issue by not converting the request to json but send as object. Though the error provided is very generic and could not identify the main issue. Upon asking to someone has experienced in ebay integration, the main issue is to provide all the needed in the headers.
public HttpResponseMessage PostHttpResponse(string requestUri, object data)
{
using (var client = CreateHttpClient())
{
try
{
HttpResponseMessage response = client.PostAsJsonAsync(requestUri, data).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
GetErrorsResponse(response);
throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
}
}
catch (HttpRequestException ex)
{
throw ex;
//return null;
}
}
}
And in the httpclient needs to add the header.
private HttpClient CreateHttpClient()
{
var client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string baseAddress = WebApiBaseAddress;
if (string.IsNullOrEmpty(baseAddress))
{
throw new HttpRequestException("There is no base address specified in the configuration file.");
}
client.Timeout = new TimeSpan(0, 5, 59);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
client.DefaultRequestHeaders.Add("Accept-Language", "en-US");
client.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("LegacyUse", "true");
return client;
}

Even with a successful access Token I get a 401 unauthorized in my Get() async method?

Currently I have to async methods Post() & Get(). For my Post() method is returning a access token and if you look at the bottom of my post method I am calling my Get() in there also, for the simple reason of being able to call string result in my get. but even with a successful access token I Keep getting a 401 unauthorized Status code, why?
Click to view error in VS
namespace APICredential.Controllers
{
[RoutePrefix("api")]
public class ValuesController : ApiController
{
[HttpGet, Route("values")]
public async Task<string> Post()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");
var parameters = new Dictionary<string, string>()
{
{"grant_type", "password"}, //Gran_type Identified here
{"username", "admin#encompass:BE11200822"},
{"password", "Shmmar****"},
{"client_id", "gpq4sdh"},
{"client_secret", "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9#A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU"},
{"scope", "lp"}
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v1/token")
{
Content = new FormUrlEncodedContent(parameters)
};
HttpResponseMessage response = await client.SendAsync(request);
string resulted = await response.Content.ReadAsStringAsync();
await Get(resulted);
return resulted;
}
}
[HttpGet, Route("values/get")]
public async Task<string> Get(string resulted)
{
string res = "";
using (var client = new HttpClient())
{
// HTTP POST
client.BaseAddress = new Uri("https://api.elliemae.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/encompass/v1/loans/{ea7c29a6-ee08-4816-99d2-fbcc7d15731d}?Authorization=Bearer "+resulted+"&Content-Type=application/json").Result;
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
}
return res;
}
The following is missing:
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Accesstoken);
This is your default header once you insert this then you have premission to getstring data from whatever your URL is...
code will look like this:
public async Task<string> Get(string Accesstoken)
{
string res = "";
using (var client = new HttpClient())
{
Accesstoken = Accesstoken.Substring(17, 28);
client.BaseAddress = new Uri("https://api.elliemae.com/");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Accesstoken);
var response = client.GetAsync("encompass/v1/loans/ea7c29a6-ee08-4816-99d2-fbcc7d15731d").Result;
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}

HttpClient PostAsync returns error 404 Not found in .net core 2.0

I am trying to call the webapi using httpclient. but it's not recognizing method and always throw 404 error.
My api Action method is like this.
[Route("AddEmployee")]
[HttpPost]
public async Task<IActionResult> PostTEmployee([FromBody]Employee emp)
{ // doing something here}
And the calling method is like below
using (var httpClient = new HttpClient())
{i
String BaseUrl = "http://ip:port/";
httpClient.BaseAddress = new Uri(BaseUrl);
AuthenticationHeaderValue parsedAuthToken = null;
bool authParsed = AuthenticationHeaderValue.TryParse(authToken, out parsedAuthToken);
if (authParsed)
{
httpClient.DefaultRequestHeaders.Authorization = parsedAuthToken;
}
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string serialisedData = JsonConvert.SerializeObject(emp);
HttpContent content = new StringContent(serialisedData, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await httpClient.PostAsync("AddEmployee", content);
if (response.IsSuccessStatusCode)
{
}
}
I am stuck with this issue from 2 days. Not sure what is the mistake? please help me.
Totally a wild guess but is your endpoint /api/AddEmployee not /AddEmployee?
try changing
response = await httpClient.PostAsync("AddEmployee", content);
To
response = await httpClient.PostAsync("api/AddEmployee", content);

Deserialize byte[] from ASP Web Api IHttpActionResult

I am trying work out the correct & best way to deserialize the response from a Asp.Net Web Api method that returns byte[].
The Web Api method looks like this
public IHttpActionResult Get()
{
byte[] content = GetContent();
return Ok(content);
}
I am calling the endpoint
string content;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = await client.GetAsync("api/v1/thecorrectpath");
if (response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
}
}
When I read the response into content it is in the format below
<base64Binary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">SfSEjEyNzE9MNgMCD2a8i0xLjcNJeLjzC...R4Cg==</base64Binary>
What would be a best practice way to convert this response into a byte[]?
I would use json.net for this.
Web API:
public string Get()
{
byte[] content = GetContent();
var data = JsonConvert.SerializeObject(content);
return data;
}
Client:
private static async Task GetData()
{
string content;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:23306/");
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response = await client.GetAsync("home/get");
if (response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<byte[]>(content);
}
}
}
You can return binary data from a Web Api method.
The ms object is a memory stream
You might want to set a more specific ContentType
On the server:
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
Then on the client:
response.Content.ReadAsByteArrayAsync();
First, install nuget package Microsoft.AspNet.WebApi.Client ;
Then use the generic extension method of http content:
c#
var result = await response.Content.ReadAsAsync<byte[]>();
It should works!

Categories