dotnet无法用角前端识别控制器

发布于 2025-02-11 22:42:53 字数 2533 浏览 2 评论 0原文

我创建了以下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:

enter image description here

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:

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我恋#小黄人 2025-02-18 22:42:53

我终于找到了这个问题。
通过Dotnet CLI生成的项目,配置A proxy.conf.js它指定了将URL重定向到服务器的,/weatherforecast是唯一允许的URL。这就是为什么添加的端点 /WeatherForeCast奏效的原因,并且在额外的控制器文件中不行。

为了使其适用于其他端点,请在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:42175';

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

module.exports = PROXY_CONFIG;

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:

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:42175';

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

module.exports = PROXY_CONFIG;
月亮坠入山谷 2025-02-18 22:42:53

替换为:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

对此:app.mapcontrollers();

,您的URL会如下:https:// localhost:444416/person/person/adddata

注意:使用aroute> [route> [oute> [oute> [控制器])]带有“ [控制器]”参数的属性,在URL中,控制器名称以大写字母开始

update

也尝试替换此Builder.Services。 AddControllersWithViews();
为此:builder.services.addcontrollers();因为您不将控制器与视图使用

Replace this:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

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 letter

Update

Also try to replace this builder.Services.AddControllersWithViews();
to this: builder.Services.AddControllers(); because you don't use controller with views

月下凄凉 2025-02-18 22:42:53

这是因为Action Result类型代表各种HTTP状态代码。

您有一个task&lt; actionResult&lt; person&gt;&gt; endpoint返回类型,但是您正在尝试返回null null 没有定义的代码状态,因此需要将其包装在OK中()或notfound()方法,等等。

[HttpPost("addData")]
public ActionResult<Person> Post(Person person)
{
    Console.WriteLine("I am here");
    return OK(person);
}

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 return null with no defined code status, so it needs to be wrapped with Ok() or NotFound() methods, etc.

[HttpPost("addData")]
public ActionResult<Person> Post(Person person)
{
    Console.WriteLine("I am here");
    return OK(person);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文