7.3 KiB
Frontend Backend sample with tye run
This tutorial will demonstrate how to use tye run to run a multi-project application. If you haven't so already, follow the Getting Started Instructions to install tye.
Running a single application with tye run
-
Make a new folder called
microserviceand navigate to it:mkdir microservice cd microservice -
Create a frontend project:
dotnet new razor -n frontend -
Run this new project with
tyecommand line:tye run frontendWith just a single application, tye will do two things: start the frontend application and run a dashboard. Navigate to http://localhost:8000 to see the dashboard running.
The dashboard should show the
frontendapplication running.- The
Logscolumn has a link to view the streaming logs for the service. - the
Bindingscolumn has links to the listening URLs of the service.
Navigate to the
frontendservice using one of the links on the dashboard.The dashboard will use port 8000 if possible. Services written using ASP.NET Core will have their listening ports assigned randomly if not explicitly configured.
- The
Running multiple applications with tye run
-
Create a backend API that the frontend will call inside of the
microservices/folder.dotnet new webapi -n backend -
Create a solution file and add both projects
dotnet new sln dotnet sln add frontend backendYou should have a solution called
microservice.slnthat references thefrontendandbackendprojects. -
If you haven't already, stop the existing
tye runcommand usingCtrl + C. Run thetyecommand line in the folder with the solution.tye runThe dashboard should show both the
frontendandbackendservices. You can navigate to both of them through either the dashboard of the url outputted bytye run.⚠️ The
backendservice in this example was created using thewebapiproject template and will return an HTTP 404 for its root URL.
Getting the frontend to communicate with the backend
Now that we have two applications running, let's make them communicate. By default, tye enables service discovery by injecting environment variables with a specific naming convention. For more information on, see service discovery.
-
Add a NuGet.config to add the
dotnet-corepackage source.Paste the following into
nuget.configin themicroservice/directory.<?xml version="1.0" encoding="utf-8"?> <configuration> <packageSources> <clear /> <add key="dotnet-core" value="https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" /> <add key="nuget" value="https://api.nuget.org/v3/index.json" /> </packageSources> </configuration> -
Open the solution in your editor of choice.
-
Add a file
WeatherForecast.csto thefrontendproject.using System; namespace frontend { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }This will match the backend
WeatherForecast.cs. -
Add a file
WeatherClient.csto thefrontendproject with the following contents:using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace frontend { public class WeatherClient { private readonly JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; private readonly HttpClient client; public WeatherClient(HttpClient client) { this.client = client; } public async Task<WeatherForecast[]> GetWeatherAsync() { var responseMessage = await this.client.GetAsync("/weatherforecast"); var stream = await responseMessage.Content.ReadAsStreamAsync(); return await JsonSerializer.DeserializeAsync<WeatherForecast[]>(stream, options); } } } -
Add a reference to the
Microsoft.Tye.Extensions.Configurationpackage to the frontend projectdotnet add frontend/frontend.csproj package Microsoft.Tye.Extensions.Configuration --version "0.1.0-*" -
Now register this client in
Startup.csclass inConfigureServicesof thefrontendproject:public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddHttpClient<WeatherClient>(client => { client.BaseAddress = Configuration.GetServiceUri("backend"); }); }This will wire up the
WeatherClientto use the correct URL for thebackendservice. -
Add a
Forecastsproperty to theIndexpage model underPages\Index.cshtml.csin thefrontendproject.public WeatherForecast[] Forecasts { get; set; }Change the
OnGetmethod to take theWeatherClientto call thebackendservice and store the result in theForecastsproperty:public async Task OnGet([FromServices]WeatherClient client) { Forecasts = await client.GetWeatherAsync(); } -
Change the
Index.cshtmlrazor view to render theForecastsproperty in the razor page:@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> Weather Forecast: <table class="table"> <thead> <tr> <th>Date</th> <th>Temp. (C)</th> <th>Temp. (F)</th> <th>Summary</th> </tr> </thead> <tbody> @foreach (var forecast in @Model.Forecasts) { <tr> <td>@forecast.Date.ToShortDateString()</td> <td>@forecast.TemperatureC</td> <td>@forecast.TemperatureF</td> <td>@forecast.Summary</td> </tr> } </tbody> </table> -
Run the project with
tye runand thefrontendservice should be able to successfully call thebackendservice!When you visit the
frontendservice you should see a table of weather data. This data was produced randomly in thebackendservice. The fact that you're seeing it in a web UI in thefrontendmeans that the services are able to communicate.
Next Steps
Now that you are able to run a multi-project application with tye run, move on to the Frontend Backend Deploy Sample to learn how to deploy this application to Kubernetes.