dotnet无法用角前端识别控制器
我创建了以下PersonController.cs:
using Microsoft.AspNetCore.Mvc;
using PersonApi.Models;
namespace donau_lead_generator.Controllers;
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private readonly ILogger<PersonController> _logger;
public PersonController(ILogger<PersonController> logger)
{
_logger = logger;
}
[HttpPost("addData")]
public Task<ActionResult<Person>> Post(Person person)
{
Console.WriteLine("I am here");
return null;
}
以及以下服务:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Person } from './person';
@Injectable()
export class HomeService {
constructor(
private http: HttpClient) {
}
/** POST: add a new user to the database */
addUser(user: Person): Observable<Person> {
return this.http.post<Person>("person/addData", user);
}
}
在这样的组件中被调用:
this.homeService.addUser(newUser).subscribe(user => {console.warn(user)
}, error => console.error(error)); //maybe create Person
我知道返回值等还不正确,但是主要问题是尚未识别端点:
我的program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
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();
如果我将方法添加到预先生成的(WeatherForeCast)端点上一切都起作用。
我的文件夹结构:
编辑
我按照答案中的要求将其更改为:
[HttpPost("addData")]
public ActionResult<Person> Post(Person person)
{
Console.WriteLine("I am here");
return Ok(person);
}
但是,它仍然抛出相同的404错误。
I have created the following PersonController.cs:
using Microsoft.AspNetCore.Mvc;
using PersonApi.Models;
namespace donau_lead_generator.Controllers;
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private readonly ILogger<PersonController> _logger;
public PersonController(ILogger<PersonController> logger)
{
_logger = logger;
}
[HttpPost("addData")]
public Task<ActionResult<Person>> Post(Person person)
{
Console.WriteLine("I am here");
return null;
}
And the following service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Person } from './person';
@Injectable()
export class HomeService {
constructor(
private http: HttpClient) {
}
/** POST: add a new user to the database */
addUser(user: Person): Observable<Person> {
return this.http.post<Person>("person/addData", user);
}
}
Which is called in the component like this:
this.homeService.addUser(newUser).subscribe(user => {console.warn(user)
}, error => console.error(error)); //maybe create Person
I know that the return value etc. is not correct yet, but the main problem is that the endpoint is not recognized:
My Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
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();
If I add the method to the pre generated (weatherforecast) endpoint everything works.
My folder structure:
EDIT
I changed it to, as requested in an answer:
[HttpPost("addData")]
public ActionResult<Person> Post(Person person)
{
Console.WriteLine("I am here");
return Ok(person);
}
However, it still throws the same 404 not found error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我终于找到了这个问题。
通过Dotnet CLI生成的项目,配置A
proxy.conf.js
它指定了将URL重定向到服务器的,/weatherforecast
是唯一允许的URL。这就是为什么添加的端点 /WeatherForeCast奏效的原因,并且在额外的控制器文件中不行。为了使其适用于其他端点,请在
proxy.conf.js
中添加人员:I finally found the problem.
The generated project via the dotnet cli, configures a
proxy.conf.js
where it specifies which urls are redirected to the server and/weatherforecast
is the only url allowed. Thats why the endpoint added in /weatherforecast worked and in an extra controller file not.To make it work for other endpoints add person in
proxy.conf.js
:替换为:
对此:
app.mapcontrollers();
,您的URL会如下:https:// localhost:444416/person/person/adddata
注意:使用
aroute> [route> [oute> [oute> [控制器])]
带有“ [控制器]”参数的属性,在URL中,控制器名称以大写字母开始update
也尝试替换此
Builder.Services。 AddControllersWithViews();
为此:
builder.services.addcontrollers();
因为您不将控制器与视图使用Replace this:
to this:
app.MapControllers();
And your url will be like: https://localhost:44416/Person/addData
Note: When using the
[Route("[controller]")]
attribute with the "[controller]" parameter, in the URL the controller name begins with an uppercase letterUpdate
Also try to replace this
builder.Services.AddControllersWithViews();
to this:
builder.Services.AddControllers();
because you don't use controller with views这是因为
Action Result
类型代表各种HTTP状态代码。您有一个
task&lt; actionResult&lt; person&gt;&gt;
endpoint返回类型,但是您正在尝试返回null
null 没有定义的代码状态,因此需要将其包装在OK中()或notfound()方法,等等。This is because the
ActionResult
types represent various HTTP status codes.You have an
Task<ActionResult<Person>>
endpoint return type, but you are trying to returnnull
with no defined code status, so it needs to be wrapped with Ok() or NotFound() methods, etc.