Reputation: 817
So, I have been watching and learning .net core for few days now. I have built functioning API (with swagger) There is controller which I do use for now, which corresponds with my problem (Doubt there is problem with it, but to be complete):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BrambiShop.API.Data;
using BrambiShop.API.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BrambiShop.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CategoriesController : ControllerBase
{
private BrambiContext _context;
public CategoriesController(BrambiContext context)
{
_context = context;
}
// GET: api/ItemVariants
[HttpGet]
public async Task<IEnumerable<Category>> GetAsync()
{
return await _context.Categories.ToListAsync();
}
// GET: api/ItemVariants/5
[HttpGet("{id}")]
public async Task<Category> GetAsync(int id)
{
return await _context.Categories.FindAsync(id);
}
// POST-add: api/ItemVariants
[HttpPost]
public async Task<IActionResult> PostAsync([FromBody] Category item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Categories.Add(item);
await _context.SaveChangesAsync();
return Ok();
}
// PUT-update: api/ItemVariants/5
[HttpPut("{id}")]
public async Task<IActionResult> PutAsync(int id, [FromBody] Category item)
{
if (!_context.Categories.Any(x => x.Id == id))
return NotFound();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Categories.Update(item);
await _context.SaveChangesAsync();
return Ok();
}
// DELETE: api/ItemVariants/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(int id)
{
var itemToDelete = _context.Categories.Find(id);
if (itemToDelete != null)
{
_context.Categories.Remove(itemToDelete);
await _context.SaveChangesAsync();
return Ok();
}
return NoContent();
}
}
}
Ok so, where is my problem. My problem lies in this method:
public async void OnGet()
{
Categories = await _Client.GetCategoriesAsync();
}
Which lies in my index.cshtml.cs.
The GetCategoriesAsync itself:
using BrambiShop.API.Models;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace BrambiShop.UI.Services
{
public interface IApiClient
{
Task<List<BrambiShop.API.Models.Category>> GetCategoriesAsync();
}
public class ApiClient : IApiClient
{
private readonly HttpClient _HttpClient;
public ApiClient(HttpClient httpClient)
{
_HttpClient = httpClient;
}
public async Task<List<Category>> GetCategoriesAsync()
{
var response = await _HttpClient.GetAsync("/api/Categories");
return await response.Content.ReadAsJsonAsync<List<Category>>();
}
}
}
Thats is where I get the TaskCanceled exception. I have no clue, what is wrong here. It doesnt make any sense to me. Startup.cs defining HttpClient
services.AddScoped(_ =>
new HttpClient
{
BaseAddress = new Uri(Configuration["serviceUrl"]),
Timeout = TimeSpan.FromHours(1)
});
services.AddScoped<IApiClient, ApiClient>();
And this is the ReadAsJsonAsync method
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace BrambiShop.UI
{
public static class HttpClientExtensions
{
private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();
public static async Task<T> ReadAsJsonAsync<T>(this HttpContent httpContent)
{
using (var stream = await httpContent.ReadAsStreamAsync())
{
var jsonReader = new JsonTextReader(new StreamReader(stream));
return _jsonSerializer.Deserialize<T>(jsonReader);
}
}
public static Task<HttpResponseMessage> PostJsonAsync<T>(this HttpClient client, string url, T value)
{
return SendJsonAsync<T>(client, HttpMethod.Post, url, value);
}
public static Task<HttpResponseMessage> PutJsonAsync<T>(this HttpClient client, string url, T value)
{
return SendJsonAsync<T>(client, HttpMethod.Put, url, value);
}
public static Task<HttpResponseMessage> SendJsonAsync<T>(this HttpClient client, HttpMethod method, string url, T value)
{
var stream = new MemoryStream();
var jsonWriter = new JsonTextWriter(new StreamWriter(stream));
_jsonSerializer.Serialize(jsonWriter, value);
jsonWriter.Flush();
stream.Position = 0;
var request = new HttpRequestMessage(method, url)
{
Content = new StreamContent(stream)
};
request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/json");
return client.SendAsync(request);
}
}
}
It all just comes to this error:
Do anybody actualy know what is wrong and can maybe direct me the right way? I hope so, I have been unable to solve this for past 4 hours.
Sincerely thanks.
__
I should also mention that sometimes it loads, and when I do something like
Debug.WriteLine(Categories.Count);
It gives me the right count, so data are loaded
(also with writing out Names with foreach)
Upvotes: 4
Views: 16018