【问题标题】:.NET 6 Controllers Only Default "WeatherForecastController" works, all others are not found.NET 6 Controllers Only Default \"WeatherForecastController\" works, all others are not found
【发布时间】:2022-11-24 03:47:14
【问题描述】:

对于大多数默认的 .NET 6 网站(使用 Angular),我试图添加一些控制器,但我添加的任何控制器似乎都不起作用,它们都返回 404(加上一些 HTML)。

然而,即使将内容更改为与新控制器相同,默认控制器“WeatherForecastController”仍然有效。

除了名称之外,我的 2 个控制器完全相同:

using Microsoft.AspNetCore.Mvc;

namespace TestWebsite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "OK";
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace TestWebsite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class OtherController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "OK";
        }
    }
}

“WeatherForecastController”的作品:

“其他控制器”返回 404:

Program.cs(字面上未经编辑):

public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services
                .AddControllersWithViews();

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

真的在这里不知所措,这完全没有意义。

编辑:我刚刚发现当我通过 http 和 http 端口调用时,两个控制器都按预期工作,为什么 https 有这个问题?

【问题讨论】:

  • 设置你的app.MapControllerRoute()后可能会丢失app.MapControllers();
  • @EricRobinson 没什么区别,只是发现它在 http 下正常工作,但是由于某种原因它只是 https 有这个问题

标签: c# angular api controller .net-6.0


【解决方案1】:

是ClientApp下的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:25215';

const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
   ],
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  }
]

module.exports = PROXY_CONFIG;

默认情况下它只有/weatherforecast,这意味着角度服务器只将这些请求转发给.NET,我将其更改为/api/*并将我的控制器[Route]更改为api/[controller],现在一切都按预期工作。

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 2022-06-16
    • 2019-12-15
    • 1970-01-01
    • 2015-12-30
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多