Giter Club home page Giter Club logo

blazor-starter's Introduction

Blazor Starter Application

This template contains an example .NET 8 Blazor WebAssembly client application, a .NET 8 C# Azure Functions, and a C# class library with shared code.

Getting Started

  1. Create a repository from the GitHub template and then clone it locally to your machine.

  2. In the Api folder, copy local.settings.example.json to local.settings.json

  3. Continue using either Visual Studio or Visual Studio Code.

Visual Studio 2022

Once you clone the project, open the solution in the latest release of Visual Studio 2022 with the Azure workload installed, and follow these steps:

  1. Right-click on the solution and select Configure Startup Projects....

  2. Select Multiple startup projects and set the following actions for each project:

    • Api - Start
    • Client - Start
    • Shared - None
  3. Press F5 to launch both the client application and the Functions API app.

Visual Studio Code with Azure Static Web Apps CLI for a better development experience (Optional)

  1. Install (or update) the Azure Static Web Apps CLI and Azure Functions Core Tools CLI.

  2. Open the folder in Visual Studio Code.

  3. Delete file Client/wwwroot/appsettings.Development.json

  4. In the VS Code terminal, run the following command to start the Static Web Apps CLI, along with the Blazor WebAssembly client application and the Functions API app:

    In the Client folder, run:

    dotnet run

    In the API folder, run:

    func start

    In another terminal, run:

    swa start http://localhost:5000 --api-location http://localhost:7071

    The Static Web Apps CLI (swa) starts a proxy on port 4280 that will forward static site requests to the Blazor server on port 5000 and requests to the /api endpoint to the Functions server.

  5. Open a browser and navigate to the Static Web Apps CLI's address at http://localhost:4280. You'll be able to access both the client application and the Functions API app in this single address. When you navigate to the "Fetch Data" page, you'll see the data returned by the Functions API app.

  6. Enter Ctrl-C to stop the Static Web Apps CLI.

Template Structure

  • Client: The Blazor WebAssembly sample application
  • Api: A C# Azure Functions API, which the Blazor application will call
  • Shared: A C# class library with a shared data model between the Blazor and Functions application

Deploy to Azure Static Web Apps

This application can be deployed to Azure Static Web Apps, to learn how, check out our quickstart guide.

blazor-starter's People

Contributors

aaronpowell avatar anthonychu avatar c0g1t8 avatar csharpfritz avatar eduherminio avatar eilon avatar hannahzhuswe avatar sikebe avatar thomasgauvin avatar vijayrkn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blazor-starter's Issues

Cors issues

The client gives errors that cors doesn't allow the client and server(api) to be run on the same machine.
The local.settings.example.json file which containts { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" }, "Host": { "LocalHttpPort": 7071, "CORS": "*", "CORSCredentials": false } }

Should be renamed to local.settings.json

This should fix the issue

Found Azure Functions Core Tools v4 which is incompatible with your current Node.js v20.12.2.

D:\DEV\TedcoStaticWebAppV4> swa start http://localhost:5000 --api-location http://localhost:7071

Welcome to Azure Static Web Apps CLI (1.1.7)


  • WARNING: This emulator may not match the cloud environment exactly. *
  • Always deploy and test your app in Azure. *

✖ Found Azure Functions Core Tools v4 which is incompatible with your current Node.js v20.12.2.
✖ See https://aka.ms/functions-node-versions for more information.
PS D:\DEV\TedcoStaticWebAppV4>

VSCode: Only Starts Azure Functions, not Blazor WebAssembly

When running the default task with vscode, it only starts and attaches to Azure Functions backend, it does not start the webassembly frontend

I had to initiate a separate window and define this task

    {
      "name": "Start Blazor",
      "type": "blazorwasm",
      "request": "launch",
      "cwd": "${workspaceFolder}/Client",
      "browser": "edge"
    }

And start it to then be able to use the webapp.

Is it possible to start/debug both simultaneously without doing two separate VSCode windows?

Could not load type 'System.Random' from assembly 'System.Runtime, Version=4.2.2.0

Sadly this template is not working out of the box anymore.
After merging the pull requests I was finally able to compile the solution.

After running the webapp I get this error when calling the Azure Function:
Could not load type 'System.Random' from assembly 'System.Runtime, Version=4.2.2.0

I can't find how to fix this.
I've used the template before with .NET3.1 and that worked fine.
Very sad that the template is no longer working after updating to .NET6.
I wonder how this template is tested ;)

.NET 6.0 version?

Hi there - is there a version of this codebase which works with .NET 6.0?

TIA!

TypeLoadException in .NET 6 in-process project (dotnet6-playwright branch) after adding package Microsoft.Azure.WebJobs.Extensions.CosmosDB

Note: This is not necessarily a Blazor SWA issue (and I realize I'm using an outdated branch -- see "Background" below) but since Blazor SWA is a particular configuration most people seem unfamiliar with I'm checking here first for ideas.

Repro steps:

  1. Create a project based on blazor-starter, branch dotnet6-playwright.
  2. Follow instructions to start/run the site locally using the "Api" project for Azure functions (Api and Client are startup projects). Observe a working site.
  3. Open Nuget Package Manager and add Microsoft.Azure.WebJobs.Extensions.CosmosDB to the Api project.
  4. Start the project again.

Expected:
Site works the same as before

Actual:
Execution stops with the following exception (see below for call stack):

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'Microsoft.Azure.WebJobs.ParameterBindingData' from assembly 'Microsoft.Azure.WebJobs, Version=3.0.34.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
  Source=Microsoft.Azure.WebJobs.Extensions.CosmosDB

Note: The following alternate steps 2 and 3 do not exhibit the error (using isolated rather than in-process):

  1. Follow instructions to start/run the site locally using the "ApIsolatedi" project for Azure functions (ApiIsolated and Client are startup projects). Observe a working site.
  2. Open Nuget Package Manager and add Microsoft.Azure.**Functions.Worker.**Extensions.CosmosDB to the ApiIsolated project.

Background:
I have a large web app based on the blazor-starter template from last year, when both isolated and in-process were options, and .NET 6.0 was the latest. Since the template default was to use in-process, that's what I used when initially creating my project. My project uses Cosmos DB including CosmosDB binding attributes. I had been using the Cosmos DB .NET SDK v2 and needed to upgrade to v3 for functionality. After doing the initial code update for the Cosmos SDK (not insignificant and must be done all at once), I finally ran it and got this TypeLoadException. I decided to go back to the clean blazor-starter template and try it, and the error still happened. It appears that if I use an isolated process I won't have this problem, However, if there is an easy way to solve this error (e.g. by adding another reference) I would welcome that rather than having to change my project to using an isolated process right now. Cosmos DB bindings are supposed to work with in-process Functions per https://learn.microsoft.com/en-us/azure/azure-functions/functions-add-output-binding-cosmos-db-vs-code?tabs=in-process%2Cv1&pivots=programming-language-csharp so I am not sure if it is something specific with this template.

Callstack:

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'Microsoft.Azure.WebJobs.ParameterBindingData' from assembly 'Microsoft.Azure.WebJobs, Version=3.0.34.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
  Source=Microsoft.Azure.WebJobs.Extensions.CosmosDB
  StackTrace:
   at Microsoft.Azure.WebJobs.Extensions.CosmosDB.CosmosDBExtensionConfigProvider.Initialize(ExtensionConfigContext context)
   at Microsoft.Azure.WebJobs.Host.DefaultExtensionRegistryFactory.Create() in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\DefaultExtensionRegistryFactory.cs:line 38
   at Microsoft.Azure.WebJobs.WebJobsServiceCollectionExtensions.<>c.<AddWebJobs>b__2_0(IServiceProvider p) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsServiceCollectionExtensions.cs:line 57
   at DryIoc.Registrator.<>c__DisplayClass27_0.<RegisterDelegate>b__0(IResolverContext r)
   at DryIoc.Scope.TryGetOrAdd(ImMap`1 items, Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Scope.GetOrAdd(Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Factory.ApplyReuse(Expression serviceExpr, Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.Factory.GetDelegateOrDefault(Request request)
   at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType, Object serviceKey, IfUnresolved ifUnresolved, Type requiredServiceType, Request preResolveParent, Object[] args)
   at DryIoc.Scope.TryGetOrAdd(ImMap`1 items, Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Scope.GetOrAdd(Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Factory.ApplyReuse(Expression serviceExpr, Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.Factory.GetDelegateOrDefault(Request request)
   at DryIoc.Container.ResolveAndCacheDefaultFactoryDelegate(Type serviceType, IfUnresolved ifUnresolved)
   at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType, IfUnresolved ifUnresolved)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Azure.WebJobs.WebJobsServiceCollectionExtensions.<>c.<AddWebJobs>b__2_6(IServiceProvider p) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsServiceCollectionExtensions.cs:line 97
   at DryIoc.Registrator.<>c__DisplayClass27_0.<RegisterDelegate>b__0(IResolverContext r)
   at DryIoc.Scope.TryGetOrAdd(ImMap`1 items, Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Scope.GetOrAdd(Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Factory.ApplyReuse(Expression serviceExpr, Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.Factory.GetDelegateOrDefault(Request request)
   at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType, Object serviceKey, IfUnresolved ifUnresolved, Type requiredServiceType, Request preResolveParent, Object[] args)
   at DryIoc.Scope.TryGetOrAdd(ImMap`1 items, Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Scope.GetOrAdd(Int32 id, CreateScopedValue createValue, Int32 disposalOrder)
   at DryIoc.Factory.ApplyReuse(Expression serviceExpr, Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.ReflectionFactory.CreateExpressionOrDefault(Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.ReflectionFactory.CreateExpressionOrDefault(Request request)
   at DryIoc.Factory.GetExpressionOrDefault(Request request)
   at DryIoc.Factory.GetDelegateOrDefault(Request request)
   at DryIoc.Container.ResolveAndCacheDefaultFactoryDelegate(Type serviceType, IfUnresolved ifUnresolved)
   at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType, IfUnresolved ifUnresolved)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Microsoft.Azure.WebJobs.Script.WebHost.WebJobsScriptHostService.<UnsynchronizedStartHostAsync>d__52.MoveNext()

Question: adding Microsoft Authentication to this?

Hi there - this isn't so much an issue as a question.

How would I go about adding Microsoft Authentication to this? So many of the tutorial resources start with a new project which has authentication selected on creation ("create a new app with Authentication = Microsoft Authentication", or "use this CLI command which sets the auth") but I've been struggling with adapting this app to use authentication with Azure AD.

Any help would be greatly appreciated - if there's a better place to ask such questions please let me know.

Rich

Playwright 'storeReports' job failure

In the Playwright tests, the storeReports job attempts to publish into a MSFT intern project repository (here).
Is there guidance around configuring this job when using this repo as a template? Should it be deleted for the general public?

Integrate test run

Probably because I'm new to Github actions, but I can't figure out how to integrate unit tests in this template. The normal steps like setup, restore and build aren't viisble and so I'm at a loss how to do that. Any suggestions, docs, hints or solutions?

Visual Studio Debugging crashes when using FileInput control in Blazor SWA

Hi @anthonychu,

I've been using SWA and has been early adapter and built a Blazor web app for managing insurance leads.

Recently, I've used the latest setup of SWA (i.e. which uses port 4280 based on your video and all the literature) for new Blazor web app and this web app contains file upload feature.
What happens is in a simple page that has one InputFile control, when a file gets selected with this control, the VS 2022 runtime/debug stops working and it states the process exited.
I tried with some 3rd party file upload controls first and then resorted to Microsoft InputFile control, same issue does exist.

Could you please take a look in your own setup and see if this happens for Blazor apps?

Thank you,
Mohammad

Anyone get this error when launching ?

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]

Azure Functions Core Tools
Core Tools Version: 4.0.5504 Commit hash: N/A +f829589bca9e7404c76db163c2d904326be8d347 (64-bit)
Function Runtime Version: 4.28.3.21820

Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
Can't determine project language from files. Please use one of [--csharp, --javascript, --typescript, --java, --python, --powershell, --custom]
[2024-02-14T14:16:47.345Z] No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).
For detailed output, run func with --verbose flag.
[2024-02-14T14:16:52.318Z] Host lock lease acquired by instance ID '0000000000000000000000009EB8CBB7'.

(vs 2022) Basic clone & build of Api project does not build, Dotnet 6 incompatibility with System.Runtime.CompilerServices.Unsafe 4.5.0

reproduction:

  1. clone project.
    (add shared back into the sln as it crashes otherwise) I see there is another pull request for that.
  2. right click of API project click build.

This is the output regardless of cleaning the api project, deleting the obj folder etc....

"logs": [
{
"code": "NU1202",
"level": "Error",
"message": "Package System.Runtime.CompilerServices.Unsafe 4.5.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0). Package System.Runtime.CompilerServices.Unsafe 4.5.0 supports: uap10.0.16300 (UAP,Version=v10.0.16300)",
"libraryId": "System.Runtime.CompilerServices.Unsafe",
"targetGraphs": [
"net6.0"
]

}
2021-11-17 16_16_40-BlazorStaticWebApps - Microsoft Visual Studio Preview

2021-11-17 16_18_39-BlazorStaticWebApps - Microsoft Visual Studio Preview

Template-created Azure Static Web App + Blazor WASM + built-in Function + MSAL: Inconsistent authentication status

I originally created this issue because I thought something was wrong with the way staticwebapp.config.json worked with the template. However, it turned out to be an issue with my attempt at authentication. The only relevance this now has to this template is that I created the project in question using the template. (Also a couple of staticwebapp.config.json questions below.) But since I have an issue here and can't delete it, I thought I would include more detail about what I know so far about my actual problem -- especially since I referred to a blog post by Anthony Chu for most of my attempts at getting authentication and authorization to work.

Repro steps:
1- Created a new Blazor WASM project from the https://github.com/staticwebdev/blazor-starter template.

2- Added code for MSAL authentication as follows:

  • Added package reference to Microsoft.Authentication.WebAssembly.Msal (6.0.1) in Client project
  • In index.html, added script line <script src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script> above the script line for blazor.webassembly.js
  • In Program.cs, added (before last line):
	builder.Services.AddMsalAuthentication(options =>
	{
	    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
	});
	        <div class="top-row px-4 auth">
	           <LoginDisplay />
	        </div>

3- Created an app registration in Azure Portal with the following settings:

  • Supported account types: Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts
  • Redirect URI --
    ○ Single-page application (SPA)
    http://localhost:5000/authentication/login-callback
  • Under Authentication:
    ○ Added https://my_static_web_app_url/authentication/login-callback
    ○ Implicit grant and hybrid flows -- selected only "ID tokens"
  • Other settings: Kept defaults

4- Under Client\wwwroot, in appsettings.json and appsettings.Development.json, added the following:

	  "AzureAd": {
	    "Authority": "https://login.microsoftonline.com/directory_(tenant)_id_from_app_registration",
	    "ClientId": "application_(client)_id_from_app_registration",
	    "ValidateAuthority": true
	  }

5- Published by submitting code changes to Github and going through the auto-deploy process

6- Ran website on dev machine and in "production" and verified that the Login button worked (I was able to log in with my personal Microsoft account and the UI changed to show me my name)

7- Navigated to https://my_static_web_app_url/.auth/me

Expected:
When I'm logged in, see a populated "clientPrincipal" record like:

	{
	  "clientPrincipal": {
	    "identityProvider": "aad",
	    "userId": "cff1e24b84b84e5ba2f19abc05d81293",
	    "userDetails": "[email protected]",
	    "userRoles": [
	      "anonymous",
	      "authenticated"
	    ]
	  }
	}

When I'm not logged in, see a null "clientPrincipal" record like:

	{
	  "clientPrincipal": null
	}

Actual:
Sometimes when I'm logged in (i.e. the login control shows my name), I see a null clientPrincipal. Sometimes when I'm not logged in (i.e. the login control shows a link for "Log in"), I see a populated clientPrincipal.

Repro Repo: https://github.com/mkb13/flaky-login
Azure Static Web App: https://jolly-hill-0f81f2b03.azurestaticapps.net/

Notes:

  • I tried to protect the "Fetch Data" tab as described here: https://anthonychu.ca/post/blazor-auth-azure-static-web-apps/ (not in this repro repo). (I did not use AddStaticWebAppsAuthentication, and I used staticwebapp.config.json instead of routes.json.) I noticed it didn't seem to be working consistently -- I thought there was something wrong with my usage of staticwebapp.config.json but then I realized it was the .auth/me that was not as expected.

  • I am using Edge (browser). I finally got the clientPrincipal to show up after going into my Static Web App and adding a fake role to my account. After that, clientPrincipal showed up all the time, whether I was logged in or not. But it was still null when I used Edge in "InPrivate" mode.

  • My assumption is I do not need to worry about the details of parsing the client principal found at https://docs.microsoft.com/en-us/azure/static-web-apps/user-information?tabs=javascript because they are handled by MSAL (and anyway I think I should see them at /.auth/me and my problem is they're not always there).

  • Sometimes when running under the debugger on my dev machine, when I log in using my Microsoft account, the login screen seems to wait forever. I assume this is just an issue with debug mode because I haven't seen it in "production", but just thought I'd mention it. (It says "Waiting for browser.event..." in the status bar and never returns, but when I run it again I'm logged in.)

  • Here's my staticwebapp.config.json after changing to protect the /api part (not in repro repo):

	{
	  "routes": [
	    {
	      "route": "/api/*",
	      "allowedRoles": [ "authenticated" ]
	    }
	  ],
	  "navigationFallback": {
	    "rewrite": "/index.html"
	  }
	}

Regarding this --

  • The staticwebapp.config.json doesn't do anything when running on my dev machine. I'm always able to access the WeatherForecast API, despite there being no /.auth/me or equivalent (even when I'm supposedly logged in). Is this expected?
  • The navigationFallback component doesn't seem to do anything anywhere. Maybe I'm misunderstanding what it's supposed to do, but if I put something random like https://my_static_web_app_url/foo, I just see the error message for not found routing from App.razor ("Sorry, there's nothing at this address."). What is it actually supposed to do?

Client fails to fetch data from API

Hi,

I've run through the getting started steps on VS 2022 and VS Code with Azure Static Web App CLI on two separate machines and the Fetch Data request fails on the client each time on the following line

forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("/api/WeatherForecast") ?? new WeatherForecast[]{};

Using the debugger I can see that the request is successfully sent to the API endpoint and the function returns the data correctly.

The exception on the client is as follows

System.Net.Http.HttpRequestException: TypeError: Failed to fetch
---> System.Runtime.InteropServices.JavaScript.JSException: TypeError: Failed to fetch
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at System.Net.Http.Json.HttpClientJsonExtensions.d__13`1[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at BlazorApp.Client.Pages.FetchData.OnInitializedAsync() in C:\source\blazorstaticdemo\blazorstaticdemo\Client\Pages\FetchData.razor:line 45

Create Artifact Container failed

If using private github repo you will get the following error: "Create Artifact Container failed: Artifact storage quota has been hit. Unable to upload any new artifacts"

This is because the cron default cron job in the tests is scheduled to run every hour.

Visual Studio 2022 and Local Authentication

The instructions in the README tell you to start the Static Web Apps CLI in the Visual Studio Code instructions, but they don't mention it in the Visual Studio 2022 instructions. Visual Studio 2022 will need the Static Web Apps CLI running, and you will need to access it on its proxy port if you try to work with authentication locally.

To get Visual Studio 2022 working with authentication locally I needed to:

  1. Start the Static Web Apps CLI and leave it running: swa start http://localhost:5000
  2. Access the app on port 4280 instead of 5000.

A more integrated solution was to:

  1. Add "launchUrl": "http://localhost:4280/", to the launchSettings.json client profile.
  2. Install the Command Task Runner (64-bit) extension.
  3. Create a StaticWebApp.cmd file in the solution root with swa start http://localhost:5000 in it.
  4. Create a commands.json file in the solution root to run StaticWebApp.cmd when the project opens:

{ "commands": { "Tools": { "fileName": "cmd.exe", "workingDirectory": ".", "arguments": "/c StaticWebApp.cmd" } }, "-vs-binding": { "ProjectOpened": [ "Tools" ] } }

Fix: I would like to see running the Static Web Apps CLI with Visual Studio 2022 addressed in the README or another solution implemented to get authentication working locally.

SWA CLI Fails to Start the Application

I followed the ReadMe directions for Visual Studio Code. Installed the latest VS Code v1.76.1 on Windows 11. Installed Azure Static Web Apps CLI and Azure Functions Core Tools CLI per the ReadMe file. Deleted the appsettings.Development.json file per the ReadMe.

When running the command "swa start http://localhost:5000 --api-location http://localhost:7071" , it attempts to start the application and eventually times out with this output:

[swa] - Waiting for http://localhost:5000 to be ready
[swa] ✖Waiting for http://localhost:5000 to be ready
[swa] ✖ Could not connect to "http://localhost:5000". Is the server up and running?
[swa] node "C:\Users\myusername\AppData\Roaming\npm\node_modules@azure\static-web-apps-cli\dist\msha\server.js" exited with code 0

Any ideas how to make this work?

Edit: I also tried to run and debug the Client/Server option and receive error "Unable to launch browser: "Could not open ...:5001/_framework/debug/ws-proxy?browser=ws%3A%2F%2F127.0.0.1%3A4477%2Fdevtoo..."

Edit2: Using the option to run and debug Client/Server is successfully launching the Azure Function Host but the error is happening after that when it tries to launch the wasm app in browser. If I wait for the Function Host to successfully start and ignore the launch error I can manually browse to http://localhost:5000 and the app is working properly. So perhaps if I just resolve the launch issue that will be sufficient.

Fresh clone sln does not build

After a fresh clone, building the solution fails as it's missing the Shared library containing the WeatherForecast class.

Client fails to fetch data from API

Greetings.

I wanted to try out this starter project and according to the readme file:

  • Create a repository from the GitHub template and then clone it locally to your machine.
  • In the ApiIsolated folder, copy local.settings.example.json to local.settings.json
  • Continue using either Visual Studio or Visual Studio Code.

While there is no local.settings.json in this project, the fix for this is add in a new file with the same name.

However, running the project and then navigating to the classic weather forecast page, I get the following error:

System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. blazor.webassembly.js:1 ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. blazor.webassembly.js:1 at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan1 bytes)
blazor.webassembly.js:1 at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
blazor.webassembly.js:1 at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
blazor.webassembly.js:1 at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
blazor.webassembly.js:1 at System.Text.Json.Utf8JsonReader.Read()
blazor.webassembly.js:1 at System.Text.Json.Serialization.JsonConverter1[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) blazor.webassembly.js:1 --- End of inner exception stack trace --- blazor.webassembly.js:1 at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex) blazor.webassembly.js:1 at System.Text.Json.Serialization.JsonConverter1[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
blazor.webassembly.js:1 at System.Text.Json.JsonSerializer.ReadCore[WeatherForecast[]](Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo, ReadStack& state)
blazor.webassembly.js:1 at System.Text.Json.JsonSerializer.ContinueDeserialize[WeatherForecast[]](ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack, JsonTypeInfo jsonTypeInfo)
blazor.webassembly.js:1 at System.Text.Json.JsonSerializer.d__761[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() blazor.webassembly.js:1 at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__51[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
blazor.webassembly.js:1 at System.Net.Http.Json.HttpClientJsonExtensions.d__291[[BlazorApp.Shared.WeatherForecast[], Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() blazor.webassembly.js:1 at BlazorApp.Client.Pages.FetchData.OnInitializedAsync() in \Client\Pages\FetchData.razor:line 46

Other than adding the "local.settings.json" file and making sure the api project file did include it, nothing else was changed from the starter project.

Please advise and thanks in advance!

Tutorial failing on github-ci "Build and Deploy Job"

Hi,

i was following the instructions on

https://docs.microsoft.com/de-de/azure/static-web-apps/deploy-blazor

with no variations. But the github ci fails:

`App Directory Location: '/' was found.
No Api directory specified. Azure Functions will not be created.
Starting to build app with Oryx
Azure Static Web Apps utilizes Oryx to build both static applications and Azure Functions. You can find more details on Oryx here: https://github.com/microsoft/Oryx
---Oryx build logs---

Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx
You can report issues at https://github.com/Microsoft/Oryx/issues

Oryx Version: 0.2.20210410.1, Commit: <>, ReleaseTagName: <>

Build Operation ID: <>
Repository Commit : <>

Detecting platforms...
Could not detect any platform in the source directory.
Error: Could not detect the language from repo.

---End of Oryx build logs---
Oryx was unable to determine the build steps. Continuing assuming the assets in this folder are already built. If this is an unexpected behavior please contact support.
Finished building app with Oryx
Failed to find a default file in the app artifacts folder (/). Valid default files: index.html,Index.html.
If your application contains purely static content, please verify that the variable 'app_location' in your workflow file (located in .github/workflows) points to the root of your application.
If your application requires build steps, please validate that a default file exists in the build output directory.

`

Does someone know what I am doing wrong?

This template pushed my Github Free account into a paid tier in one day.

Playwright generates artifacts that build up and didn't clear by themselves (after one day) and pushed my Github account into a paid tier ( I mean I was using next to nothing in terms of space before this 'template' it pushed my account over on storage.)

I'm only writing this because this template made me get out my credit card after being unable to push to my current project (old version template static blazor live app.) disrupting my workflow locking my actions / account up.... the fact that the template has a tigger makes it worse.
I'd also question why playwright is even in a blazor starter template, I like playwright but talk about unnecessary, I'd assume a 'starter' template should be accessible.

Could not hit function API running template in VS 2022

When I created a repo from the template and then cloned it to my local machine I was not able to hit the API endpoint in the functions app.

I need to update the appsettings.Development.json file with
{ "BaseAddress": "http://localhost:7071/" }

Then I also needed to update the Program.cs file with
var baseAddress = builder.Configuration["BaseAddress"] ?? builder.HostEnvironment.BaseAddress; builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(baseAddress) });
replacing
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) })

Basically copying from the previous / older template

Then I was able to get the data from the function app when I navigated to the fetchdata page

I also needed to add the Shared project as it was not included in the solution when I opened it in VS
(it was in the cloned repo, just not referenced in the solution when I opened it)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.