Blazor FAQ - Troubleshooting

How do you fix “The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time” error in Blazor Server application?

In a Blazor Server application, if you want to use both AllowCredentials() and AllowAnyOrigin() with respect to CORS settings, then add SetIsOriginAllowed(Func<string,bool> predicate) under ConfigureServices in the Startup.cs file instead of using AllowAnyOrigin(). See the following code snippet. 

[Startup.cs] 

public void ConfigureServices(IServiceCollection services) 

{ 

        …… 

        …… 

        services.AddCors(options => 

        { 

        options.AddPolicy("Open", builder => 

        builder.SetIsOriginAllowed(_ => true). 

        AllowAnyMethod(). 

        AllowAnyHeader(). 

        AllowCredentials()); 

    }); 

}

Refer to this link for more information.

Permalink
How do I install Blazor in Visual Studio 2019?

Follow the below steps to install Blazor in Visual Studio 2019.

Prerequisite:

Install the latest Blazor Extension from the Visual Studio Marketplace. This step makes Blazor templates available to Visual Studio 2019.

For steps to install Visual studio 2019, refer to the “Install Visual Studio” article.

Permalink
Error CS1061 ‘IJSRuntime’ does not contain a definition for ‘Current’.

Error CS1061 ‘IJSRuntime’ does not contain a definition for ‘Current’ and no accessible extension method ‘Current’ accepting a first argument of type ‘IJSRuntime’ could be found (are you missing a using directive or an assembly reference?)

Solution

In ASP.NET Core 3.0.0-preview3, the Microsoft.Interop.JSRuntime.Current has been removed.

@inject IJSRuntime JsRuntime;

@code {
    protected void CallJSMethod()
    {
        JSRuntime.InvokeAsync<bool>("JSMethod");
    }
}

Reference link: https://github.com/aspnet/AspNetCore/issues/8117

Permalink
The name ‘RegisteredFunction’ does not exist in the current context in Blazor.

Solution:

‘RegisteredFunction’ does not exist anymore from Blazor v0.5.0.

JavaScript code

function JSMethod() {
   document.getElementById('demop').innerText = "JavaScript Method invoked";
}

Blazor code

@page "/jsinterop"

@inject IJSRuntime JsRuntime;

@code {
    protected void CallJSMethod()
    {
        JSRuntime.InvokeAsync<bool>("JSMethod");
    }
}
Permalink
Object of type ‘Blazor.NetCore.Client.Pages.ChildContent’ does not have a property matching the name ‘ChildContent’.

If the parameter name and component name are same, don’t change the parameter name. Otherwise you will get this error.

Change the file and keep the parameter name the same. It will work now.

Permalink
Error: System.ArgumentException: Cannot instantiate implementation type ‘Microsoft.AspNetCore.Blazor.Services.UriHelperBase’ for service type ‘Microsoft.AspNetCore.Blazor.Services.IUriHelper’. Now what?

Here is the solution.

This works after adding a dependency injection for NavigationManager, and IUriHelper has been replaced with NavigationManager.

@inject NavigationManager Navigation;

Reference link:

https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-9/

Permalink
Visual Studio crashes when I paste markup in the functions block. How do I fix this?

Yes, this is a known issue while working with Visual Studio. You can track the details in this GitHub thread. [Issue Resolved]

Permalink
Issue—System.InvalidOperationException: Object of type ‘Microsoft.AspNetCore.Components.Forms.InputText’ does not have a property matching the name ‘type’.

As of now, there is no support for including arbitrary attribute support for the built-in input component <InputText />. You have to remove the type attribute to resolve this issue.

There is a plan for including the type=”password” attribute for the <InputText> component, which can be tracked in this GitHub thread. [Issue Resolved]

Permalink
I could not find the property of window when calling the JavaScript method in Blazor using JS interop.

You have to refer to the JavaScript method implemented JS (external-script.js) file in index.html properly and then call the function from .NET using IJSRuntime.

[wwwroot/index.html]

<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>
    <script src="external-script.js"></script>
</body>

[wwwroot/external-script.js]

window.methods = {
    print: function (message) {
        return "from js " + message
    }
}

[Pages/Index.razor]

@inject IJSRuntime JSRuntime

@code {
  private async void PrintMessage()
  {
    Console.WriteLine(await JSRuntime.InvokeAsync<string>("methods.print", "here is the message"));
  }

}
Permalink
What if I am unable to use or validate the password type input text in a Blazor form?

For now, there is no password-type built-in input component. You can track the availability of <InputText type=”password” /> in this thread. [Issue Resolved]

   <input type="password"   placeholder="Password" />
Permalink
How do I debug a Blazor application client-side?
  1. Run the Blazor application in Debug mode in Chrome 70 and above.
  2. With the focus of the Blazor application in the Chrome browser, run the following
  • Shift+Alt+D on Windows/Linux
  • Shift+Cmd+D on macOS

Refer to Debug Blazor applications for more information.

Permalink
Is BrowserUriHelper not accessible in Blazor applications?

The BrowserUriHelper has been renamed WebAssemblyUriHelper. Use WebAssemblyUriHelper to achieve your requirement.

Refer to the thread BrowserUriHelper is dead, right? for more information.

Permalink
How do you debug a client-side Blazor app in VS Code?

For now, there is no option to debug a client-side Blazor application in VS Code, although the debugging of server-side applications is possible.

Refer to the thread debug Blazor in VS Code for more information.

Permalink
Where are the compiled CS files generated for Razor files of Blazor applications?

You can find the generated CS files in the following location of Blazor client-side applications.

{{APPLICATION_ROOT}}/obj/Debug/netstandard2.0/Razor/Pages

Permalink
Why do tasks returned from JSRuntime.InvokeAsync during OnInitAsync never finish in Blazor?

This is a known bug and is resolved in the upcoming release of Blazor Preview 3. [Issue Resolved]

[wwwroot/index.html]

<script>
        window.interopDuringOnInit = function () {
            return "Hello World";
        }
</script>

[Razor]

@code {
    string Greeting;

    protected override async Task OnInitializedAsync()
    {
        try
        {            
            Greeting = await JSRuntime.InvokeAsync<string>("interopDuringOnInit");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Could not invoke interop during OnInit, " + ex.ToString());
        }
    }
}

Refer to the thread Tasks returned from JSRuntime.InvokeAsync during OnInitAsync never finishes for more information.

Permalink
What do I do if the name ‘JSRuntime.Current.InvokeAsync‘ does not exist in the current context?

After Blazor 3.0.0-preview3, the Current was deprecated, and you have to use something like the following code example.

Before

await JSRuntime.Current.InvokeAsync<string>("methods.print", "here is the message")

After

await JSRuntime.InvokeAsync<string>("methods.print", "here is the message")
Permalink
I’m getting this issue: the type or namespace name ‘Mvc’ does not exist in the namespace ‘Microsoft.AspnetCore’ (are you missing an assembly reference?).

While upgrading Blazor applications, you many encounter these issues. You have to do the following changes to properly run the application:

  • Update all Microsoft.AspNetCore.Blazor.* package references to 3.0.0-preview4-19216-03.
  • Remove any package reference to Microsoft.AspNetCore.Components.Server.
  • Remove any DotNetCliToolReference to Microsoft.AspNetCore.Blazor.Cli and replace with a package reference to Microsoft.AspNetCore.Blazor.DevServer.
  • In client Blazor projects, remove the <RunCommand>dotnet</RunCommand> and <RunArguments>blazor serve</RunArguments> properties.
  • In client Blazor projects, add the <RazorLangVersion>3.0</RazorLangVersion> property.
  • Rename all _ViewImports.cshtml files to _Imports.razor.
  • Rename all remaining .cshtml files to .razor.
  • Rename components.webassembly.js to blazor.webassembly.js
  • Remove any use of the Microsoft.AspNetCore.Components.Services namespace and replace with Microsoft.AspNetCore.Components as required.
  • Update server projects to use endpoint routing.
// Replace this:
app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
});

// With this:
app.UseRouting();

app.UseEndpoints(routes =>
{
    routes.MapDefaultControllerRoute();
});
  • Run dotnet clean on the solution to clear out old Razor declarations.

Reference link : Go through the upgrade section https://devblogs.microsoft.com/aspnet/blazor-now-in-official-preview/. You can also check this thread for more information.

Permalink
What do I do if the Blazor extension fails to be installed?

Yes, the Blazor failing to install VS 16.1 Preview 3 and .NET 4.8 is a known issue, which is fixed in this thread.

Permalink
Why is the DateTime 24-hours conversion to AM/PM is not working?

You have to use the format-value string “yyyy-MM-ddTHH:mm” to work with AM/PM conversion properly.

<input type="datetime-local" id="Test" name="Test" class="form-control" @bind="@testDateTime" format-value="yyyy-MM-ddTHH:mm" />

@code {
    DateTime testDateTime { get; set; } = new DateTime(2019, 12, 15, 16, 45, 15);
}

Refer to this thread for more information.

Permalink
Every time I need to run the application manually, live reloading is not working. Why?

For now, you must manually run the application to reflect the changes in the browser. There is an issue tracker for the live reloading feature.

Permalink
Issue—Blazor – System.InvalidOperationException: Object of type

‘BlazorDataBinding.Pages.Counter’ has a property matching the name ‘IncrementValue’, but it does not have [ParameterAttribute] or [CascadingParameterAttribute] applied.

You must mention the [Parameter] attribute for the component attributes.

 [Parameter]
 private int IncrementValue { get; set; } = 5;
Permalink
Issue—Blazor – InvalidOperationException: Cannot identify unique bin directory for Blazor app.

Open the application in File Explorer and delete the bin/Debug & bin/Release folders. Now, clean and run the application.

Permalink
Issue—Blazor ValueChanged event did not fire with built-in input elements

Yes, this is a known issue in Blazor. You can track the issue link in the ValueChanged event not fired thread.

The following code snippet will work. You have to update the model manually because handling the ValueChanged event does not let you use the @bind-Value we need to use ValueExpression instead of @bind-Value.

<EditForm Model="person">
    <DataAnnotationsValidator />
    <div class="form-group">
        <label for="name">Name</label>
        <InputText ValueChanged="@ValueChange" Value="@person.FirstName" ValueExpressions= "@( () => @person.FirstName )" Class="form-control" Id="name" />
    </div>
</EditForm>

@code { 
    Person person = new Person();
    public void ValueChange()
    {
        Console.WriteLine(person.FirstName);
    }
}

Instead, you can also use the OnValidSubmit form event to get and process the value.

<EditForm Model="person" OnValidSubmit="@ValueChange">
  <DataAnnotationsValidator />
   <div class="form-group">
     <label for="name">Name</label>
     <InputText @bind-Value="@person.FirstName" Class="form-control" Id="name" />
   </div>
</EditForm>

@code { 
    Person person = new Person();
    public void ValueChange()
    {
        Console.WriteLine(person.FirstName);
    }
}
Permalink
What if the component ref/instance is not working? Or the component ref is undefined?

The component instance filed is populated along with the component after rendering completion. You must access the component instance in the OnAfterRenderAsync or OnAfterRender methods of the Blazor lifecycle.

@page "/"
  
 <Counter IncrementValue="10" @ref="counter"></Counter>
  
 @code {
  
     private Counter counter;    
  
     protected override void OnAfterRender()
     {
         base.OnAfterRender();
         counter.increase(); //access counter instance here
     }
 }
Permalink
Issue—Blazor: IJSRuntime.InvokeAsync serialization broken for arrays of objects.

The InvokeAsync accepts only params object[] args, so the array of objects is parsed as a single, top-level entry in args. You have to pass the array of objects as a single object by casting. The following code only passes the single array object.

[JS helper]

window.debugOut = function(content) {
 console.dir(content);
}

[Razor]

await JSRuntime.InvokeAsync<object>("debugOut", new Person[] {
     new Person{FirstName=" Nancy",LastName=” Davolio”},
      new Person{FirstName=" Andrew", LastName=” Fuller”}
});

By casting the array into an object, it retrieves all the values.

await JSRuntime.InvokeAsync< object >("debugOut", (object) new Person[] {
     new Person{FirstName=" Nancy",LastName=” Davolio”},
      new Person{FirstName=" Andrew", LastName=” Fuller”}
});

Refer to the following link for more information. https://github.com/aspnet/AspNetCore/issues/8743

Permalink
I’m missing the Blazor template in Visual Studio.

From the official documentation, in order to get started with Blazor, you have to install the latest preview of VS 2019 with the ASP.NET and web development workload along with the Blazor extension.

Also, In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core 3.0 are selected.

Refer to this getting started link for more information about Blazor prerequisites.

Permalink
What if I am unable to run Blazor apps in Visual Studio Code?

There are multiple reasons the Blazor application wouldn’t run in Visual Studio Code.

Scenario 1: The omnisharp Visual Studio Code is not installed properly in the machine to run the application. Refer to the getting started with Blazor using Visual Studio Code documentation.

Scenario 2: Running a Blazor app with F5 in Visual Studio is not supported in omnisharp, which is tracked in this GitHub issue.

For now, you can run the Blazor application using the following dotnet CLI command in the application root folder.

 dotnet run
Permalink