Edu*_*ord 1 .net c# endpoint angular
我创建了以下 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;
}
Run Code Online (Sandbox Code Playgroud)
以及以下服务:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在组件中这样调用:
this.homeService.addUser(newUser).subscribe(user => {console.warn(user)
}, error => console.error(error)); //maybe create Person
Run Code Online (Sandbox Code Playgroud)
我知道返回值等还不正确,但主要问题是端点未被识别:
我的程序.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();
Run Code Online (Sandbox Code Playgroud)
如果我将该方法添加到预先生成的(天气预报)端点,一切都会正常。
我的文件夹结构:
编辑
我按照答案中的要求将其更改为:
[HttpPost("addData")]
public ActionResult<Person> Post(Person person)
{
Console.WriteLine("I am here");
return Ok(person);
}
Run Code Online (Sandbox Code Playgroud)
但是,它仍然抛出相同的 404 未找到错误。
我终于找到了问题所在。通过 dotnet cli 生成的项目配置一个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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
981 次 |
| 最近记录: |