HttpClient System.Threading.Tasks.TaskCanceledException:'操作被取消了。'

问题描述 投票:-1回答:1

所以,我一直在观看和学习.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异常的地方。我不知道,这里有什么问题。它对我没有任何意义。 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写出姓名)

asp.net-core .net-core asp.net-core-2.2
1个回答
2
投票

将void更改为Task:

 public async Task OnGet() 
© www.soinside.com 2019 - 2024. All rights reserved.