Blazor page name conflict with controller

Greg Arzoomanian 46 Reputation points
2021-08-26T23:48:41.767+00:00

I'm seeing some odd behavior creating a client-side Blazor app with a web api. It appears you can't create a page with the same name as a web api controller.

In particular, I create the project with Visual Studio 2019, selecting the "Blazor WebAssembly App" template:
126941-image.png

I then set the "ASP.NET Core hosted" checkbox so I'll have a server side project for accessing a database at some point.
126924-image.png

This creates an app with Client, Server, and Shared projects. The Server project has a controller for the WeatherForecast data.

At this point I can run the default app. It has a FetchData page on the client that pulls data from the WeatherForecastController using the web api.

Now what happens if I try to create my own page to access the WeatherForecastData? Well, if I name it "Forecast" (using "Add->Razor Component"), and add a @Anonymous directive "/forecast", everything works fine.

But if I create a Razor Component with the name "WeatherForecast", and add a @Anonymous directive "/weatherforecast", I get a build error:

126951-image.png

I can only assume that there's a conflict between the client page "weatherforecast" and the server controller "WeatherForecastController".

So my questions are:
1.) Is this correct?
2.) Where can I read more about this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,623 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,595 questions
0 comments No comments
{count} vote

Accepted answer
  1. Chao Deng-MSFT 801 Reputation points
    2021-08-27T03:15:30.983+00:00

    Hi @Greg Arzoomanian ,

    You need to introduce the correct namespace in FetchData, like this:

    @code {  
        private WebApplication89.Shared.WeatherForecast[] forecasts;  
      
        protected override async Task OnInitializedAsync()  
        {  
            forecasts = await Http.GetFromJsonAsync<WebApplication89.Shared.WeatherForecast[]>("WeatherForecast");  
        }  
      
    }  
    

    Result:
    lsqvt.png


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    ChaoDeng


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.