Location>code7788 >text

Getting Started with Vue+.NET 8 Web Api Record (I)

Popularity:541 ℃/2024-07-25 14:05:41

Doing projects that you feel are interesting or address your needs as a starter, I think it helps and doesn't feel so boring.

What should a minimal front-end and back-end separation project look like?

I think it's just a button on the front end, click it to send a get request to the back end, get the data and display it on the front end.

In conjunction with the recent interest in SemanticKernel, the idea of doing a demo learning like this, where the user clicks a button that returns a complimentary sentence.

Vue:

One of the obvious benefits of separating the front-end and back-end is that you can use multiple front-ends using the same back-end service, for example, I also made one of these client apps with Avalona, and can share this back-end service as well, as shown below:

Getting Started with the .NET 8 Web Api

Select the Web Api template:

image-20240725092622106

Additional information:

image-20240725093117690

There are a few things to note here:

What does it mean to configure https?

Configuring HTTPS refers to setting up and enabling the Secure Hypertext Transfer Protocol (HTTPS) on a web server.HTTPS is a secure version of HTTP that adds an SSL/TLS encryption layer to the HTTP protocol to ensure that data is encrypted in transit between the client and the server, thereby protecting the confidentiality and integrity of the data.

What does it mean to enable OpenAPI support?

OpenAPI (formerly known as the Swagger specification) is a specification for describing, generating, consuming, and visualizing RESTful Web services. It allows developers to define all aspects of an API, including paths, operations, request parameters, responses, and authentication methods. By using the OpenAPI specification, developers can more easily create, maintain, and use API documentation, resulting in more efficient development and understandable APIs.

Enabling OpenAPI support means integrating and configuring the OpenAPI specification in a software project to be able to generate, use and present OpenAPI-compliant API documentation. This means that projects will be able to utilize OpenAPI's various tools and ecosystems to streamline the API design, development, documentation, and testing process.

What does it mean to not use a top-level statement?

In C#, "Not using top-level statements" means writing code without the top-level statements feature introduced in C# 9.0.

What does it mean to use a controller?

Controller is MVC (Model-View-Controller) in the Controller, in the Web API development, "using the controller" (Using Controllers) refers to the use of a design pattern, in which the logic of the API is organized into a class called "controller". Controllers are responsible for handling HTTP requests, executing the appropriate business logic, and returning HTTP responses.

In order to maintain the convenience and standardization, they add a layer of Model, a layer of Services:

image-20240725130842155

Now think about what service you want to add, the idea is to use SemanticKernel to access the big language model and have it return a complimentary sentence when we request it.

SemanticKernel knows right now that it's on the line to get LLM quickly integrated into our application.

Install SemanticKernel:

image-20240725131101780

Add SemanticKernelService to Services:

 public class SemanticKernelService
 {
     private readonly Kernel _kernel;
     public SemanticKernelService()
     {
         var handler = new OpenAIHttpClientHandler();
         var builder = ()
        .AddOpenAIChatCompletion(
           modelId: "Qwen/Qwen2-7B-Instruct",
           apiKey: "yoursapikey",
           httpClient: new HttpClient(handler));
         _kernel = ();
     }

     public async Task<string> Praiseyuzai()
     {
         var skPrompt = """                           
                       You're an expert at complimenting people.,Reply to a compliment。
                       yours回复应该是一句话,Not too long.,And not too short.。
                       """;
         var result = await _kernel.InvokePromptAsync(skPrompt);
         var str = ();
         return str;
     }

 }

Many people may look at the introduction of SemanticKernel will feel that can only use the OpenAI model, in fact, as long as compatible with the OpenAI format of the online model can be, the local model is also possible through the realization of the interface to achieve access to the platform chosen in this paper is a silicon-based flow of Qwen/Qwen2-7B-Instruct model, free of charge to use. The platform chosen for this paper is the Qwen/Qwen2-7B-Instruct model under in silico flow, which is free to use.

Since it is not OpenAI that needs to forward requests to the Api provided by Silicon Flow, the OpenAIHttpClientHandler class needs to be added to the model as shown below:

 public class OpenAIHttpClientHandler : HttpClientHandler
 {
     protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     {
         UriBuilder uriBuilder;
         switch (?.LocalPath)
         {
             case "/v1/chat/completions":
                 uriBuilder = new UriBuilder()
                 {
                     // Here's what you want to change. URL
                     Scheme = "https",
                     Host = "",
                     Path = "v1/chat/completions",
                 };
                  = ;
                 break;
         }

         HttpResponseMessage response = await (request, cancellationToken);

         return response;
     }

By chatting with the Big Language Model, we are providing a Prompt, and here we have the following Prompt:

  var skPrompt = """
                       You are an expert at complimenting people and replying with a one sentence compliment.
                       Your reply should be one sentence, not too long and not too short.
                       """;

The Big Language Model will respond to us based on this Prompt.

The project structure is now shown below:

image-20240725131839064

Now take this constructed service and add it to the dependency injection container:

image-20240725131923106

A more standardized approach would be to pass in an interface and an implementation class; this primer passes in the implementation class directly.

Now to see how the controller is written?

Let's start by looking at one of the controllers that come with the template:

 [ApiController]
 [Route("[controller]")]
 public class WeatherForecastController : ControllerBase
 {
     private static readonly string[] Summaries = new[]
     {
         "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
     };

     private readonly ILogger<WeatherForecastController> _logger;

     public WeatherForecastController(ILogger<WeatherForecastController> logger)
     {
         _logger = logger;
     }

     [HttpGet(Name = "GetWeatherForecast")]
     public IEnumerable<WeatherForecast> Get()
     {
         return (1, 5).Select(index => new WeatherForecast
         {
             Date = ((index)),
             TemperatureC = (-20, 55),
             Summary = Summaries[()]
         })
         .ToArray();
     }
 }

Write a controller modeled after it:

[ApiController]
[Route("[controller]")]
public class SemantickernelController : ControllerBase
{
    private readonly ILogger<SemantickernelController> _logger;
    private readonly SemanticKernelService _semanticKernelService;
    
    public SemantickernelController(ILogger<SemantickernelController> logger,SemanticKernelService semanticKernelService)
    {
        _logger = logger;
        _semanticKernelService = semanticKernelService;
    }

    [HttpGet]
    public async Task<string> Get()
    {
        _logger.LogInformation($"fulfillmentPraiserequesting timing:{}");
        var str = await _semanticKernelService.Praise();
        return str;
    }
 
}

The service class we just registered is injected in the constructor.

[HttpGet]
public async Task<string> Get()
{
   _logger.LogInformation($"fulfillmentPraiserequesting timing:{}");
   var str = await _semanticKernelService.Praise();
   return str;
}

The way this one is written is not really standardized, and you can use the laterActionResult<T>Alternative, leave it alone for now, it works.

Now start the project and the Swagger UI will pop up:

image-20240725132604898

You can debug the interface written above and try the Get request you just created:

image-20240725132824604

We just wrote

 _logger.LogInformation($"Executing Praise request Time: {}");;

You can see the information output on the console when you call the interface, as shown below:

image-20240725133048007

When the time comes, in order for us to be able to access it over the LAN, add it to Program:

image-20240725133156224

Front-end access will also need to address cross-domain issues a bit when the time comes, adding them to Program:

image-20240725133235285

Ready to go.

Up to this point, we've built a simple backend service with only one Get request using the .NET 8 Web Api.

The next installment shares parts from Vue and Avalonia.