为什么此GET操作可以处理获取数据

赛义德

活跃的成员
已加入
2020年10月21日
留言内容
34
编程经验
3-5
您好,

为什么此“获取操作”有效?关于URL吗?

这是我的代码:

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

控制器:

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

看来问题与数据库有关,请采取行动!不是获取URL

您看到任何问题吗?

谢谢
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,500
地点
弗吉尼亚州切萨皮克
编程经验
10+
您是在问为什么它有用吗?还是您在问为什么它不起作用?如果不起作用,您会遇到什么错误?
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,500
地点
弗吉尼亚州切萨皮克
编程经验
10+
听起来您正在尝试执行代码优先的Entity Framework,并跳过了允许EF实际创建数据库的步骤。欢迎来到实体框架的喜悦。希望关心EF的人可以加入这个话题来帮助您。正如我在另一个主题中所说,我个人不建议使用EF。
 
最佳 底部