所以,我已经观察和学习了几天的.net核心。我已经建立了功能正常的API(大张旗鼓) 我现在确实使用了一个控制器,它与我的问题相对应(怀疑它有问题,但有待完善):
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();
}
}
}
好的,我的问题在哪里。我的问题在于这种方法:
public async void OnGet()
{
Categories = await _Client.GetCategoriesAsync();
}
哪个位于我的index.cshtml.cs中。
GetCategoriesAsync本身:
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>>();
}
}
}
那是我获得TaskCanceled异常的地方。我不知道,这是怎么了。这对我没有任何意义。 定义HttpClient的Startup.cs
services.AddScoped(_ =>
new HttpClient
{
BaseAddress = new Uri(Configuration["serviceUrl"]),
Timeout = TimeSpan.FromHours(1)
});
services.AddScoped<IApiClient, ApiClient>();
这是ReadAsJsonAsync方法
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);
}
}
}
有人真的知道错在哪里,也许可以以正确的方式指导我吗?希望如此,过去4个小时我一直无法解决。
非常感谢。
__
我还应该提到有时加载,并且当我执行类似操作
时Debug.WriteLine(Categories.Count);
它给了我正确的计数,因此可以加载数据
(也可以使用foreach写下名称)
答案 0 :(得分:2)
将“无效”更改为“任务”:
public async Task OnGet()