当我尝试获取本地主机 ASP.NET Core Web API 时出现 304 错误

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

我刚刚使用 React 模板创建了一个 ASP.NET Core Web API。

我写了这段代码

let options = {
   method: 'GET'
}

const response = await fetch("https://localhost:44482/WeatherForecast/Get", options);

但是当我启动我的应用程序时,出现错误

304 未修改

以及回复中的此页面

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <base href="/" />
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>My App</title>
  <script defer src="/static/js/bundle.js"></script></head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
  </body>
</html>

我做错了什么?

我没有更改

program.cs
和控制器中的路由。

我在 Postman 中也遇到了同样的错误

这是我的控制器

[ApiController]
[Route("[controller]")]
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;

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

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}

这是我的 Programm.cs
using GoalJourney.Data;
using GoalJourney.Services;
using GoalJourney.Services.Interfaces;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddTransient<IGoalService, GoalService>();
builder.Services.AddSingleton<GoalDataContext>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();
c# asp.net-core fetch asp.net-core-webapi fetch-api
1个回答
0
投票

为了解决这个问题,我将站点和 Web api 部分分开。
我创建了一个新的 Web API 项目并移动了控制器、模型和其他服务器内容。
我还修复了 CORS 问题,因为我将从 localhost:44482 获取到 localhost:7005。

builder.Services.AddCors(options =>
{
    options.AddPolicy( "AllowAll",
        policy  =>
        {
            policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        });
});

app.UseCors("AllowAll");
© www.soinside.com 2019 - 2024. All rights reserved.