Execute Commands From Browser Address bar .Net Core
As a .net Core developer you may be familiar with executing command against your web application using the terminal window using the .Net CLI command utility. At the same time you may encounter a situation where you may need to execute commands from the browser window.
Let us say you have a Web API application that is only used to process front end requests and response with the data or whatever response from the requested service. An end user tried to browse this API from the browser and you need to show a message in the browser like: "This application has no user interface, it is just a data access layer. Please close this window or tab :-)". Everything happens in the Program.cs file.
open Program.cs
write the following
|
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); |
we use app.MapGet to do the trick, this function takes the first parameter as a string refers to the address bar. The default is
|
app.MapGet("/", () => "Hello World"); |
we can easily change it to the following
|
app.MapGet("/", () => "This application has no user interface, it is just a data access layer. Please close this window or tab :-)"); |
This might looks funny to the end user, but we need to go further.
What if we need to execute something like database seed function.
The database seed function is the function that runs and executes some SQL commands against the database to seed the database tables with the initial data required for the first run; like adding the admin user or adding the first sample product.
Without further delay the code is as follows:
|
app.MapGet("/seed", async () => await RunSeeding() == "1" ? Results.Text("Database seeding has been successfully completed.") : Results.Ok(_seedResult)).AllowAnonymous(); |
here the command is (seed) we just write (www.domain.com/seed) or locally (http://localhost:3333/seed). The function that is needed to be called is (RunSeeding()) which is asynchronous function (notice) we used the key words async - await and if the function returned "1" it is successfull and the user is notified with the message ("Database seeding has been successfully completed.") or return the error message from the function.
We can also allow the anonymous user to run this command using (AllowAnonymous()) in the end.
I hope this explains a new way to the end user (system admin) to execute predefined commands against the web application.
Comments
Post a Comment