【问题标题】:Fetch API can't find controller in asp .net core web api applicationFetch API 在 asp .net core web api 应用程序中找不到控制器
【发布时间】:2021-10-31 01:27:37
【问题描述】:

我正在尝试使用 fetch api 将数据从我的 asp .net core web api 应用程序加载到我的 react 组件。但是当我在FetchData 组件中使用示例await fetch('weatherforecast') 来调用WeatherForecastController 时,我感到非常困惑。有用。我在示例代码中进行了调试,WeatherForecastController中的功能很好实现,但是如果我在我的项目中使用这个想法,它不起作用,我的调试功能没有达到。有人可以解释一下我的情况下 fetch api 的用法吗?

控制器类

[ApiController]
[Route("[controller]")]
public class HelloController : ControllerBase
{
    [HttpGet]
    public IEnumerable<T> Get()
    {
        //do something
    }
}

我的反应组件

const response = await fetch('Hello');

在 program.cs 中(我使用的是 .net 6)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
builder.Services.AddDbContext<T>(options =>
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "MY API", Version = "v1" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MY APP v1"));
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRouting();
app.MapControllers();
app.Run();

我在setupProxy发现了一些有趣的东西

const { createProxyMiddleware } = require('http-proxy-middleware');

const context = [
    '/weatherforecast',
    '/controllerName1',
    '/controllerName2',
];

module.exports = function (app) {
    const appProxy = createProxyMiddleware(context, {
        target: 'https://localhost:5001',
        secure: false
    });

    app.use(appProxy);
};

默认weatherforecast控制器工作,de route通过调试是正确的。但是如果我在另一个控制器中尝试它,它就不起作用。有人可以解释一下吗?

【问题讨论】:

  • 我根本不懂 ASP.NET,但你说[Route("[controller]")]fetch('Hello'); 这些名字不应该匹配吗?
  • 是的,它们应该匹配。此机制在示例代码中有效,但不适用于我。我不知道为什么。
  • 如果它们应该匹配,为什么你写它们而不是它们?让它们匹配能解决问题吗?
  • 我不太明白你的意思。但关键是我想弄清楚这个机制是如何工作的。别人说的,我也有同样的感觉,就是跟路由前缀设置有关,但是具体在哪里就不知道了。
  • 您将路线命名为controller!您正在向服务器询问名为 Hello!

标签: javascript reactjs asp.net-web-api fetch


【解决方案1】:

你能检查 Startup.cs 吗?可能您在那里设置了路由前缀。喜欢api。因此,在这种情况下,您的网址将是 /api/hello 或者配置swashbuckle,它会告诉你确切的路线,并让你选择尝试你的API

【讨论】:

  • 但是在示例代码fetch('weatherforecase') 中,当我在我的项目中使用相同的想法时,就会到达控制器。它没有用。
  • 现在可以运行 swagger 并检查 API URL 了吗?您可以通过localhost:xxxx/swagger 访问 swagger
  • 我在 localhost:xxxxx/swagger 上检查了 swagger。它显示一个空白页。顺便说一句,为了清楚起见,我发布了整个程序类。
猜你喜欢
  • 2017-11-12
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多