我无法访问网络核心 MVC 控制器中的方法



EDIT:如果我创建一个空的ASP.NET CORE WEB APP MVC,我可以让它工作。我在Angular中使用MVC时遇到了问题。SPA代理可能也有问题。

编辑2:我找到一份报告https://github.com/dotnet/aspnetcore/issues/38354我还在努力,但没有机会。

我无法访问控制器类中的公共方法。这是我的控制器:

[Route("authentication")]
public class AuthenticationController : Controller
{
[HttpGet("example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}

我也尝试了这个属性:

[Route("[controller]")]
public class AuthenticationController : Controller

当我尝试导航到localhost:PORT/authentication/example时,我得到了404。我没有使用API。我正在尝试用.net核心MVC和angular构建一个web应用程序。所以我将只是向控制器发送GET或POST请求。

这是我的程序.cs文件

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();

我坚信我的程序.cs出了问题。但我想不通。

修复:经过几天的尝试,我终于找到了答案。我不得不将我的新路由添加到proxy.conf.js文件中的proxy变量中。

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

您可以尝试一下,例如,它将适用于localhost:PORT/authentication/example

[Route("[controller]/[action]")]
public class AuthenticationController : Controller
{

public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}
//or 
public class AuthenticationController : Controller
{
[HttpGet("~/Authentication/Example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}

但是,由于您使用的是Controller作为基类,而不是ApiController,因此即使删除了所有属性路由,一切都应该正常工作。

您需要用方法/路由属性装饰控制器

尝试:

[Route("api/[controller]")]
public class AuthenticationController : Controller
{
[HttpGet("example")]
public IActionResult Example()
{
return Ok("This is the Welcome action method...");
}
}

这将创建一个可以在api/authentication/example调用的get端点

返回200状态,正文中包含文本。

惯例是,如果你的模因以动作动词开头,它可以自动找到,就像一样

public string GetExample()

然而,您不希望返回原始字符串,您总是希望返回操作结果,因为您希望使用显式HttpStatus响应代码进行包装,因此

public IActionResult<string> GetExample()

现在,我们中的许多人因为前缀而倾向于魔术作品,并且喜欢更明确,这不仅是因为属性表示法允许更多的控制,而且是为了一致性。因为几乎总是,控制器的至少一种动作方法实际上需要细粒度。

[HttpGet("example")]
public IActionResult<string> Example()

然后通常,例如,有一个id,你可以去

[HttpGet("example/id?")]
public IActionResult<string> Example([FromRoute] string id)

例如,如果你不想让它遍历所有可能从中获取变量的地方,有很多可用的选择

最新更新