0

I searched before and have tried to implement the answers to no success.

Get in Postman for the url api/blogpage returns a 200 OK.

I am stuck, seemingly painted myself into a corner, hoping that someone points out the obvious.

Thank you all

UPDATED with new insights and working code.

Error in Chrome

      Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
 ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. ```



My Razor-Component code-block

@code {
    private List<BlogItem> BlogPosts = new List<BlogItem>();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {

        BlogPosts = await Http.GetFromJsonAsync<List<BlogItem>>("GetAllBlogPosts");
    }
}
**EDIT - got a working code going** 

List<BlogItem> BlogPosts;
    protected override async Task OnInitializedAsync()
    {
        var response = await Http.GetAsync("/api/GetAllBlogPosts");
        if (response.IsSuccessStatusCode)
        {
            BlogPosts = await response.Content.ReadFromJsonAsync<List<BlogItem>>();
    enter code here

My BlogController

 [Route("api[controller]")]
    [ApiController]
    public class BlogController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        public BlogController(ApplicationDbContext context)
        {
            this._context = context;
        }
          public List<BlogItem> BlogPosts { get; set; } = new List<BlogItem>
          { 
        new BlogItem { Title = "My first blog", Summary = "My first blog ever"}
      };
    
        [HttpGet]
        [Route("GetAllBlogPosts")]
      public ActionResult<List<BlogItem>>Get()
        {
            return Ok(_context.BlogItem);
        }
**EDIT - changed the route to this - [Route("/api/GetAllBlogPosts")]**
H H
  • 263,252
  • 30
  • 330
  • 514
SinisterAlex
  • 11
  • 2
  • 4
  • The error is in your URLs - primarily the leading `/` in `/api/GetAllBlogPosts`. See [this answer](https://stackoverflow.com/a/67626931/60761) for a working sample. – H H May 26 '21 at 11:56
  • @HenkHolterman - the leading / in the /api/ works just fine. I am not sure why though as your answer makes sense ... – SinisterAlex May 26 '21 at 12:59
  • If it works fine then why this question? – H H May 26 '21 at 13:05
  • I have edited my inital question with a code that works – SinisterAlex May 26 '21 at 13:18
  • Actually it's not duplicate. Here I see a mistake: you call Http.GetAsync("/api/GetAllBlogPosts") but must add controller name after api like "api/Blog/GetAllBlogPosts" – Danil Sep 16 '22 at 11:52

3 Answers3

3

I believe your problems stems from:

BlogPosts = await Http.GetFromJsonAsync<List<BlogItem>>("GetAllBlogPosts");

This line assumes a Json result back from the API conforming to List<BlogItem>. If there is an error calling the API the result will not conform. It is the attempted deserialization of this non-confirming result that is the error being reported in your question.

To get to the real source of the problem, try this pattern:

HttpResponseMessage res = await Http.GetAsync("GetAllBlogPosts");
if (res.IsSuccessStatusCode)
{
    // Only deserialize when we did not have an API failure
    BlogPosts = res.Content.ReadFromJsonAsync<List<BlogItem>>();
}
else
{
    // Otherwise treat the response as an error message
    string errMsg = await res.Content.ReadAsStringAsync();
    Console.WriteLine(errMsg);
    throw new Exception(errMsg);
}

This will then only try to deserialize when response is successful. If the call gets an error it will read the content (error message) as a string instead. That string will tell you what the real source cause of your problem is.

Neil W
  • 7,670
  • 3
  • 28
  • 41
0

fix the action


        [Route("GetAllBlogPosts")]
      public ActionResult<List<BlogItem>> Get()
        {
            return Ok(_context.Set<BlogItem>().ToList());
        }

and try to replace

if (response.IsSuccessStatusCode)
        {
  BlogPosts = await response.Content.ReadFromJsonAsync<List<BlogItem>>();

with

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
BlogPosts = JsonConvert.DeserializeObject<List<BlogItem>>(stringData);
}
else{ ...error code}
Serge
  • 40,935
  • 4
  • 18
  • 45
  • I need to investigate further as your solution did not remove the error. Could it have something do to with json.serialization/deserialization? – SinisterAlex May 26 '21 at 08:28
0

Could it be a BOM (byte order mark) - try opening in something like notepad++, select UTF-8 encoding, save, sand try relaunching

Chris
  • 598
  • 8
  • 23