Get data from WebApi in c# - c#

I have webapi and her method:
[HttpPost, HttpGet]
[ActionName("GetData")]
public MyData GetData([FromUri] MyData data)
{
return datamanager.get(data);
}
How do I invoke this method? I.e. how do I send data parameter through query part of URL?
To invoke get method which takes no parameters I use following code:
public static async Task<myClassl> GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://sasa.com");
HttpResponseMessage response = await client.GetAsync("api/GetData");
myClassl data = await response.Content.ReadAsAsync<myClassl>();
return data ;
}
Thanks.

Try the following solution:
HttpClient client = new HttpClient();
string baseApiAddress = ConfigurationManager.AppSettings["baseApiAddress"];
client.BaseAddress = new Uri(baseApiAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response=client.GetAsync("/api/GetData",data, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{
var mydata = response.Content.ReadAsAsync<MyData>().Result;
}
else
{
Debug.WriteLine(response.ReasonPhrase);
}

Related

How would i send a payload with my post request in c#?

I am trying to login to a website and i need to send the credentials as a payload but I don't understand how payloads are sent.
public class LoginClient
{
private readonly HttpClient _client;
public LoginClient()
{
_client = new HttpClient();
}
public async Task Put()
{
using (var request = new HttpRequestMessage(HttpMethod.Post, $"https://accounts.nike.com/challenge/password/v1"))
{
using (var response = await _client.SendAsync(request))
{
}
}
}
}
You are trying to send Json, use PostAsync to set the content
var client = new HttpClient();
var url = $"https://accounts.nike.com/challenge/password/v1";
var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, data);

Task<string> does not contain a definition for GetAwaiter()

I Am trying to authenticate URL credentials but I am getting this error as:
Task does not contain a definition for 'GetAwaiter'
public class Methods
{
public static async Task<JObject> Get(string url, string username, string password)
{
var credentials = new NetworkCredential(username, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
// client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
return new JObject { response.StatusCode };
}
}
public async Task<IActionResult> Index()
{
// Methods RestMethod = new Methods();
var httpClient = new HttpClient();
var data = await Methods.Get("http://www.myportal.com/api/now/table/core_company", "user#myportal.com", "Password123");
return View();
}

Calling remote web api from mvc controller

What is the preferred way for handling web api endpoints for each controller?
For example, my MVC controller will be calling different endpoints.
These are the only ones for now, but it could change.
Also, I will be developing this locally and and deploying to development server.
http://localhost:42769/api/categories/1/products
http://localhost:42769/api/products/
public class ProductsController : Controller
{
HttpClient client;
string url = "http://localhost:42769/api/categories/1/products"; //api/categories/{categoryId}/products
public ProductsController()
{
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
// GET: Products
public async Task<ActionResult> ProductsByCategory()
{
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
var products = JsonConvert.DeserializeObject<List<GetProductsByCategoryID>>(responseData);
return PartialView(products);
}
return View("Error");
}
}
Not sure I understand you question or problem, but I would create a wrapper class for the service and then have different methods for each resource that you need to call. Always think SOLID.
Example (written by hand)
public class Client
{
private Uri baseAddress;
public Client(Uri baseAddress)
{
this.baseAddress = baseAddress;
}
public IEnumerable<Products> GetProductsFromCategory(int categoryId)
{
return Get<IEnumerable<Product>>($"api/categories/{categoryId}/products");
}
public IEnumerable<Products> GetAllProducts()
{
return Get<IEnumerable<Product>>($"api/products");
}
private T Get<T>(string query)
{
using(var httpClient = new HttpClient())
{
httpClient.BaseAddress = baseAddress;
var response= httpClient.Get(query).Result;
return response.Content.ReadAsAsync<T>().Result;
}
}
}

Calling web service asynchronously in page constructor

I need to load data on a XAML page in a windows 10 UWP application. For that I wrote code to call the web service in async task function, and I call this in page constructor. Could you please tell best way to do this? Following is my code.
public sealed partial class MyDownloads : Page
{
string result;
public MyDownloads()
{
this.InitializeComponent();
GetDownloads().Wait();
string jsonstring = result;
//code for binding follows
}
private async Task GetDownloads()
{
JsonObject jsonObject = new JsonObject
{
{"StudentID", JsonValue.CreateStringValue(user.Student_Id.ToString()) },
};
string ServiceURI = "http://m.xxx.com/xxxx.svc/GetDownloadedNotes";
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceURI);
request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
string returnString = await response.Content.ReadAsStringAsync();
result = returnString;
}
}
Instead that you need use OnNavigatedTo
because, GetDownloads().Wait() bad practice. You block UI Thread until the end of execution
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var result = await GetDownloadsAsync();
string jsonstring = result;
}
private async Task<string> GetDownloadsAsync()
{
JsonObject jsonObject = new JsonObject
{
{"StudentID", JsonValue.CreateStringValue(user.Student_Id.ToString()) },
};
string ServiceURI = "http://m.xxx.com/xxxx.svc/GetDownloadedNotes";
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceURI);
request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
string returnString = await response.Content.ReadAsStringAsync();
return returnString;
}
}

Client calling WebAPI stuck in await

I have a httpclient that is calling a WebAPI service. The GET reaches the service and returns the content but the client just keeps waiting...
Client code:
static async Task RunAsyncGet(string baseUri, string uri)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage response = await client.GetAsync(uri); // <-- stuck here
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
IEnumerable<UserAccountModel> users = await response.Content.ReadAsAsync<IEnumerable<UserAccountModel>>();
//...
}
}
}
WebAPI code:
public class UserAccountController : ApiController
{
private IRepository _repo;
public UserAccountController(IRepository repo)
{
_repo = repo;
}
public HttpResponseMessage Get()
{
var s = _repo.GetAllUserAccounts();
IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(typeof(AuthResponseModel), Request, Configuration.Formatters);
var bestMatchFormatter = result.Formatter;
var mediaType = result.MediaType.MediaType;
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<IQueryable<UserAccount>>(s, bestMatchFormatter, mediaType)
};
}
}
Thoughts?
Further up in your client code (whatever ends up calling RunAsyncGet), some code is calling Task.Wait or Task<T>.Result. That will cause a deadlock if called from the UI thread, as I explain on my blog.
The proper solution is to change that Wait/Result to use await.
This is how I ended up calling the WebAPI:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:23302");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/useraccount").Result;
if (response.IsSuccessStatusCode)
{
var t = response.Content.ReadAsAsync<IEnumerable<UserAccount>>().Result;
...
}
else
{
//Something has gone wrong, handle it here
}
}
It seems that your call to EnsureSuccessStatusCode is the likely culprit. That method actually returns a HttpResponseMessage that will have a HTTP status in the 200 range, or will throw an exception. So, you probably want something like:
static async Task RunAsyncGet(string baseUri, string uri)
{
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage response = await client.GetAsync(uri);
IEnumerable<UserAccountModel> users = await response.EnsureSuccessStatusCode().Content.ReadAsAsync<IEnumerable<UserAccountModel>>();
// ... the rest ...
}

Categories

Resources