Home > other >  Dotnet not recognizing controller with Angular frontend
Dotnet not recognizing controller with Angular frontend

Time:07-02

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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;
  • Related