none
Request for Advice on using HttpClient in a Controller RRS feed

  • Question

  •     

    private const string AmerOAuthUrl = "https://api.tdameritrade.com/v1/oauth2/token";

    [HttpGet("{symbol}")] public async Task<Cagr> GetQuoteAsync(string symbol) { using (var message = new HttpRequestMessage(HttpMethod.Post, AmerOAuthUrl)) { //Build the parameters same as before var parameters = new Dictionary<string, string> { { "application/x-www-form-urlencoded", "grant_type=refresh_token&refresh_token=kf67WLD/ZAD3XUD7iDId7+cGHdGEIu1VVT4ZgF5eN5Npm/yVuRpSJ0FdIiL57SMrR &client_id=AMN@AMER.OAUTHAP&redirect_uri=http://localhost" } }; var encodedContent = new FormUrlEncodedContent(parameters); //Set the content of the request message object to your paramaters message.Content = encodedContent; //Send the request and await the response. var response = await httpclient.SendAsync(message); if (response.StatusCode == HttpStatusCode.OK) { // Do something with response. Example get content: // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false); } }

    I get an error running this code, 'response not defined
    • Moved by CoolDadTx Friday, January 10, 2020 3:02 PM ASP.NET related
    Tuesday, January 7, 2020 12:06 AM

All replies

  • If the method's name is  GetQuoteAsync, then why are you trying to do a Post? That seems kind of strange.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

    Below is example of ServiceLayer that PayrollController on client side calls to for CRUD with the database sitting behind WebAPI. 

    IMHO, the controller should not be making calls using httpclinet directly.

    To me it doesn't matter of the controller is being used in MVC concerning a UI or the controller is used in a WebAPI that incorporates the MVC pattern as well, which is about flow control and a thin controller

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). 

    <end>

    using Entities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace ServiceLayer { public class PayRollSvc :IPayRollSvc { public List<DtoPayroll> GetAll() { var dtopayrolls = new List<DtoPayroll>(); using (var client = new HttpClient()) { var uri = new Uri("http://localhost/WebAPI/api/payroll/GetAll"); var response = client.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) throw new Exception(response.ToString()); var responseContent = response.Content; var responseString = responseContent.ReadAsStringAsync().Result; dynamic payrolls = JArray.Parse(responseString) as JArray; foreach (var obj in payrolls) { DtoPayroll dto = obj.ToObject<DtoPayroll>(); dtopayrolls.Add(dto); } } return dtopayrolls; }

    public DtoPayroll Find(int id) { DtoPayroll dto; using (var client = new HttpClient()) { var uri = new Uri("http://localhost/WebAPI/api/payroll/Find?id=" + id); HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result; if (!getResponseMessage.IsSuccessStatusCode) throw new Exception(getResponseMessage.ToString()); var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result; dynamic payroll = JsonConvert.DeserializeObject(responsemessage); dto = payroll.ToObject<DtoPayroll>(); } return dto; } public DtoPayroll FindPayRollByAuthorId(int id) { DtoPayroll dto; using (var client = new HttpClient()) { var uri = new Uri("http://localhost/WebAPI/api/payroll/FindPayRollByAuthorId?id=" + id); HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result; if (!getResponseMessage.IsSuccessStatusCode) throw new Exception(getResponseMessage.ToString()); var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result; dynamic payroll = JsonConvert.DeserializeObject(responsemessage); dto = payroll.ToObject<DtoPayroll>(); } return dto; } public void Add(DtoPayroll dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("WebAPI/api/payroll/Add", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } public void Update(DtoPayroll dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("WebAPI/api/payroll/Update", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } public void Delete(DtoId dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("WebAPI/api/payroll/Delete", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } } }


    Tuesday, January 7, 2020 1:59 AM
  • Hi,

    Has your issue been resolved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    If not, I suggest you can ask this question at the ASP.NET Forums.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 10, 2020 8:50 AM
  • This forum is for C#-specific questions only. Please post questions related to ASP.NET in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, January 10, 2020 3:02 PM