Blazor FAQ - Troubleshooting

Find answers for the most frequently asked questions
Expand All Collapse All

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

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’ 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

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

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

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

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

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

‘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

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

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

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

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

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.