Home > other >  Cannot get response from C# API controller with Angular
Cannot get response from C# API controller with Angular

Time:08-14

I'm getting started with Angular and I've created a C# (.NET 6) and Angular (14.1.2) application. And there is trouble with accessing my controller: I can't get a response from HTTP methods of my controller.
Interesting that the default 'WeatherForecastController', which is being created with a new project, works fine.

Controller:

    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        // GET: api/<ProductController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        [Route("getnumb")]
        public int GetNumber()
        {
            return 43;
        }
    }

Program.cs

using Hardware_Store_App.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddDbContext<StoreContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("defaultConnection")));

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

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.UseCors("corsapp");

app.MapControllers();
app.MapFallbackToFile("index.html"); ;

app.Run();

Error that appears in the browser's console when I'm trying to request the controller's method:

core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'api/product'
Error: Cannot match any routes. URL Segment: 'api/product'
    at ApplyRedirects.noMatchError (router.mjs:2939:16)
    at router.mjs:2921:28
    at catchError.js:10:38
    at OperatorSubscriber._error (OperatorSubscriber.js:23:1)
    at OperatorSubscriber.error (Subscriber.js:40:1)
    at OperatorSubscriber._error (Subscriber.js:64:1)
    at OperatorSubscriber.error (Subscriber.js:40:1)
    at OperatorSubscriber._error (Subscriber.js:64:1)
    at OperatorSubscriber.error (Subscriber.js:40:1)
    at OperatorSubscriber._error (Subscriber.js:64:1)
    at resolvePromise (zone.js:1211:1)
    at resolvePromise (zone.js:1165:1)
    at zone.js:1278:1
    at _ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.mjs:25579:1)
    at _ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at drainMicroTaskQueue (zone.js:585:1)

Here's what Postman returns
So I assume, maybe I have to declare controller or something

CodePudding user response:

Use just app.MapControllers();

Like so:

app.UseRouting();
app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

And make your method like this

    [HttpGet("getnumb")]
    public int GetNumber()
    {
        return 43;
    }

CodePudding user response:

Instead of having:

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

Use:

app.MapControllers();

This way .NET will look for all Controllers in your application and map them :)

Edit: You can also add swagger to more easily debug these situations:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ... other services

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

CodePudding user response:

The problem was the wrong port, I've been trying to request. I thought the server runs on the port, that opens by default in the browser. But I don't have a clue why it worked fine with the default controller...

  • Related