asp.net-core - HttpClient 系统.Threading.Tasks.TaskCanceledException : 'The operation was canceled.'

标签 asp.net-core .net-core asp.net-core-2.2

所以,我这几天一直在观察和学习 .net core。我已经构建了功能 API(大摇大摆) 我现在确实使用了一个 Controller ,这与我的问题相对应(怀疑它有问题,但要完整):

    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 异常的地方。我不知道,这里有什么问题。这对我没有任何意义。 Startup.cs 定义 HttpClient

            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);
        }
    }
}

这一切都只是出现了这个错误: enter image description here

有没有人知道什么是错的,也许可以指导我正确的方式?我希望如此,过去 4 小时我一直无法解决此问题。

衷心感谢。

__

我还应该提到,有时它会加载,当我做类似的事情时

Debug.WriteLine(Categories.Count);

它给了我正确的计数,所以数据被加载了

(也可以用 foreach 写出名称)

最佳答案

将 void 更改为任务:

 public async Task OnGet() 

关于asp.net-core - HttpClient 系统.Threading.Tasks.TaskCanceledException : 'The operation was canceled.' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677947/

相关文章:

c# - 在 Polly 重试尝试中获取完整的 URI?

c# - 作为子项的 DotNet Core .csproj 代码文件

c# - 为什么 UseStaticFiles 和 UseDefaultFiles 之间的顺序很重要?

c# - HTTP 错误 502.5 - 升级到 ASP.NET Core 2.2 后 ANCM 进程外启动失败

c# - 如何使用 JSONConvert 将变量 Result 转换为对象?

swagger - 在 ASP.NET Core 2.2 中使用 nswag 设置承载 token

c# - 如何在 Blazor Server 后端正确使用依赖注入(inject)?

c# - WebSocket 握手错误 : Unexpected response code 400

c# - 如何在.NET Core中的Web API中获取授权用户?

ubuntu - 如何将 SSL 证书添加到 asp.net core docker swarm +letsencrypt?