question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

API Controllers routes isn't working on Blazor Server Side

See original GitHub issue

Describe the bug

Defining routes / endpoints for API Controllers on a Blazor Server-Side project isn`t working. I had it working on previous Blazor versions but can’t it to work on 0.9.0-preview3-19154-02.

To Reproduce

startup.cs code:

        public void ConfigureServices(IServiceCollection services)
        {
   services.AddMvc().AddNewtonsoftJson().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
        services.AddRazorPages();
        services.AddServerSideBlazor();`

        //services.AddAuthentication(o => o.DefaultAuthenticateScheme = AzureADB2CDefaults.CookieScheme)
        //    .AddAzureADB2C(options => Configuration.Bind("AzureADB2C", options))
        //    .OnLogin(principal =>
        //    {
        //        services.BuildServiceProvider().GetRequiredService<LoginCommand>()
        //            .Execute(principal, principal.AzureID(), principal.Email(), principal.DisplayName());
        //    });

        services.AddBlazorModal();
        AddRepositories(services);
        AddCommands(services);
        AddHttpClient(services);
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //app.UseAuthentication();
        //app.UseMvcWithDefaultRoute();

        app.UseRouting();

        //app.UseMvc();

        //app.UseMvc(routes =>
        //{
        //    routes.MapRoute(
        //      name: "default",
        //      template: "{controller=Home}/{action}/{id?}");
        //});
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action}");

            endpoints.MapControllers();
            //endpoints.MapRazorPages();

            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }

API Controller:

        [Produces("application/json")]
        [Route("api/[controller]")]
        [ApiController]
        public class DataController : Controller
        {
        [HttpPost]
        [Route("UploadPhoto")]
        public async Task<string> UploadFile(UploadFileParameters file)
        {
              return null;
        }

    [HttpGet]
    [Route("Test")]
    public string Test()
    {
        return "abc";
    }
}`

Expected behavior

Posting to https://localhost:xxxxx/api/Data/UploadPhoto Or getting from: https://localhost:xxxxx/api/Data/Test should work.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
iamgmdcommented, Apr 17, 2019

@baartho I installed VS2019 16.1.0 Preview 1.0 along with the nightly build of the dotnet SDK 3.0.100-preview4-011223, Created a BlazorComponent solution and changed the Startup.cs to be as below and I was able to call a MVC controller without problems. I will assume that this will work for an API controller as well. Hope this helps.

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication1.Data;

namespace WebApplication1
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false)
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 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.UseMvcWithDefaultRoute();

            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}
0reactions
natristcommented, Oct 13, 2019

@iamgmd I managed to complete the first part of this tutorial (https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-controller?view=aspnetcore-3.0&tabs=visual-studio) following your code example.

This problem is still present with the latest out-of-the-box Visual Studio 2019 setup as of today. I’m not sure if it affects every project template, but I built mine with Blazor MVC and I had to add the lines from your comment for my controllers to work.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Not able to route to API in Blazor Server app
I'm brand new to Blazor and I'm trying to learn by converting an old website/web API project into a .Net 6 Blazor Server...
Read more >
ASP.NET Core Blazor routing and navigation
This article explains how to manage Blazor app request routing and how to use the NavLink component to create navigation links.
Read more >
Blazor not routing correctly when using Controller ...
I have a Blazor WASM app that is hosted in an aspnet application. The hosting app contains some API routes, and they all...
Read more >
Call a web API from an ASP.NET Core Blazor app
Learn how to call a web API from Blazor apps.
Read more >
Server side blazor app httpclient calls are not reaching my ...
Try this: put app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}"); }); before calling app.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found