Why this GET action can handle Fetch Data

SaeedP

Well-known member
Joined
Oct 21, 2020
Messages
99
Programming Experience
3-5
Hello,

Why this get Action works? is it about URL?

Here comes my code:

C#:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
//using Microsoft.EntityFrameworkCore;

namespace imageEditor3
{

    public class FileContext : DbContext
    {
        public DbSet<FileModel> FileModels { get; set; }
    }
    public class FileModel
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int FileId { get; set; }
        public string FileName { get; set; }
        public IFormFile FormFile { get; set; }
    }
}

Controller:

C#:
namespace imageEditor3.Controllers
{
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    
    [Route("[Controller]")]

    [ApiController]

    public class WeatherForecastController : ControllerBase
    {
        
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

      
        private readonly ILogger<WeatherForecastController> _logger;

      
        private IEnumerable<FileModel> myFile;


        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        
 
        [Route("WeatherForecast/Post")]
        [HttpPost]
        public IActionResult Post([FromForm] FileModel file)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

                using (Stream stream = new FileStream(path, FileMode.Create))
                {

                    file.FormFile.CopyTo(stream);

                }

                return StatusCode(StatusCodes.Status201Created);

            }

            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

        


        
         [Route("WeatherForecast/Get")]
        [HttpGet]
        public IEnumerable<FileModel> Get()
        {
            using (var Context = new FileContext())
            {
                 myFile = Context.FileModels.ToArray();
            }

            return myFile;
        }


    }

}

FetchData:

C#:
import React, { Component } from 'react';

export class FetchData extends Component {
  static displayName = FetchData.name;

  constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };
  }

  componentDidMount() {
    this.populateWeatherData();
  }

  static renderForecastsTable(forecasts) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>FileId</th>
            <th>FileName (C)</th>
            <th>FormFile (F)</th>
            <th>Summary</th>
          </tr>
        </thead>
        <tbody>
          {forecasts.map(forecast =>
            <tr key={forecast.FileId}>
              <td>{forecast.FileName}</td>
              <td>{forecast.FormFile}</td>
              //<td>{forecast.temperatureF}</td>
              //<td>{forecast.summary}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderForecastsTable(this.state.forecasts);

    return (
      <div>
        <h1 id="tabelLabel" >Weather forecast</h1>
        <p>This component demonstrates fetching data from the server.</p>
        {contents}
      </div>
    );
  }

  async populateWeatherData() {
      const response = await fetch('weatherforecast/weatherforecast/Get');
    const data = await response.json();
    this.setState({ forecasts: data, loading: false });
  }
}

It seems the problem is related to the database and get action! not the Get URL

Do you see any problem with it?

thanks
 
Are you asking why it works? Or are you asking why it does not work? If it doesn't work, what error are you getting?
 
Are you asking why it works? Or are you asking why it does not work? If it doesn't work, what error are you getting?
It does not work. It points to the array( ) in the Get Action and says you didn't define a database for it!
 
Sounds like you are trying to do code-first Entity Framework and skipped a step to allow EF to actually create the database. Welcome to the joys of Entity Framework. Hopefully someone who cares about EF will jump in on this thread to help you out. As I said in another thread, I personally wouldn't recommend using EF.
 
Back
Top Bottom