Tessaract
Tessaract

Reputation: 1935

Unable to setup a controller on Blazor Server

I am trying to add an MVC, or WebAPI, or whatever controller to my Blazor Server project.

I have read numerous SO questions, blogs and etc. on the matter, like this. None of them work.

No matter what I add to my "endpoints" or "app" in my "Configure" or "ConfigureServices" methods when I start my application in debug and try to make a request using Postman it times out.

I tried:

Adding controller exactly as shown in the linked answer.

Adding any and all of those in my Startup:

Neither does Postman get any answer (times out) nor does a breakpoint I've set in the "Get" method of the controller get triggered.

What can I do to get a controller working?

Upvotes: 1

Views: 2631

Answers (2)

user19633465
user19633465

Reputation: 1

I know is too late, but meaby helpfull somenone in future.
Check add Controllers in Program.cs like this

builder.Services.AddControllers();

When builder is

var builder = WebApplication.CreateBuilder(args);

And dont forget about this:

var app = builder.Build();
app.MapControllers();

app.Run();

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170148

I did the following (which "worked on my machine"):

  1. create a new BlazorApp:
dotnet new blazorserver -o BlazorApp --no-https
  1. add a controller:
namespace BlazorApp.Controllers
{
  using Microsoft.AspNetCore.Mvc;

  [ApiController]
  public class TestController : ControllerBase
  {
    [HttpGet("test")]
    public ActionResult<string> Test()
    {
      return "TODO";
    }
  }
}
  1. add endpoints.MapControllers(); to Satrtup.cs
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();            // new
    endpoints.MapBlazorHub();              // existing
    endpoints.MapFallbackToPage("/_Host"); // existing
});
  1. run the app

  2. go to http://localhost:5000/test (you'll get the "TODO" response)

  3. go to http://localhost:5000 (you'll see the Blazor page)

EDIT

@Tessaract in the comments mentioned that the site was running on HTTPS while the plain HTTP was being queried (and therefor didn't work).

Upvotes: 4

Related Questions