几天前我问了一个类似的问题,但我现在有另一个控制器的问题,对于我的生活,我不知道为什么这会返回404。
API控制器……
[Route("api/[controller]")]
[ApiController]
public class FilesController
{
private readonly IFilesService _filesService;
public FilesController(IFilesService filesService)
{
_filesService = filesService;
}
[HttpGet("{id}")]
public IEnumerable<SupportFile> GetFiles(int id) {
return _filesService.GetFiles(id);
}
[HttpGet("DownloadFile/{fileName}")]
public async Task<FileStreamResult> DownloadFile(string fileName)
{
return await _filesService.DownloadFile(fileName);
}
}
Program.cs…
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<DapperContext>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<ISupportService, SupportService>();
builder.Services.AddScoped<IFilesService, FilesService>();
builder.Services.AddControllersWithViews();
builder.Services.AddControllers();
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.MapControllers();
app.UseRouting();
app.MapDefaultControllerRoute();
app.MapFallbackToFile("index.html"); ;
app.Run();
Proxy.conf.js…
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:19229';
const PROXY_CONFIG = [
{
context: [
"/api/*"
],
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
}
]
module.exports = PROXY_CONFIG;
另一个运行良好的api控制器…
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
public User ModifyUser(AzureUser user)
{
return _userService.ModifyUser(user);
}
[HttpGet]
public IEnumerable<User> GetUsers()
{
return _userService.GetUsers();
}
}
但无论我做什么…
https://localhost:44427/api/files/123返回404。
https://localhost:44427/api/files/DownloadFile/test.csv返回404。
其他API控制器方法工作,所以端口是正确的。
其他api控制器虽然只有一个GET,每当我尝试使用属性路由添加多个GET时,它们都只是返回404。
已解决。
是proxy.conf.js.
我必须更改"/api/*"/api/* *";在上下文数组中,**似乎是一个包罗万象的对象。
您的控制器应该继承ControllerBase
类。
而不是:
public class FilesController
试试这个:
public class FilesController : ControllerBase
你试过调试吗?
ID为123或名称为test.csv的文件是否存在?
https://localhost: 44427/api/文件/123
https://localhost: 44427/api/文件/DownloadFile/test.csv
如果不是,那么服务方法可能返回null,这将导致默认的404。