ASP.NET Hosting

AI Integration in.NET Core

Let’s examine a code-based example of integrating AI with.NET Core.

The Home Screen

Let’s create a simple view to interact with the user for questions and answers.

index.cshtml

<h2>Enter your text</h2>

<form method="post">
    <div>
        <textarea id="Message" name="Message" rows="5" cols="40" class="text col-md-5"></textarea>
    </div>
    <br />
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<br />

<h3>Result :</h3>
@if (Model != null)
{
    <p>@Model</p>
}

The following is the structure of our controller. As you know, it functions like a typical MVC controller for handling user requests and responses.

HomeController.cs

using AIIntegrationDotNetCore.Models;
using AIIntegrationDotNetCore.Services;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace AIIntegrationDotNetCore.Controllers
{
    public class HomeController : Controller
    {
        //private readonly ILogger<HomeController> _logger;

        private readonly OpenAIService _openAIService;

        public HomeController(ILogger<HomeController> logger, OpenAIService openAIService)
        {
            //_logger = logger;
            _openAIService = openAIService;
        }

        [HttpPost]
        public async Task<IActionResult> Index(UserMessageRequest request)
        {
            var reply = await _openAIService.GetChatCompletionAsync(request.Message);
            ViewBag.Message = reply;
            return View("Index", reply);
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public class UserMessageRequest
        {
            public string Message { get; set; }
        }
    }
}

Most importantly, there is a separate service class to handle communication with the AI.

using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;

namespace AIIntegrationDotNetCore.Services
{
    public class OpenAIService
    {
        //private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;

        public OpenAIService(HttpClient httpClient, IConfiguration configuration)
        {
            //_httpClient = httpClient;
            _configuration = configuration;
        }

        public async Task<string> GetChatCompletionAsync(string userMessage)
        {
            var apiKey = _configuration["Gemini:ApiKey"];
            var apiUrl = _configuration["Gemini:ApiUrl"];

            string requestBody = @"{
                ""contents"": [{
                    ""parts"":[{ ""text"": """ + userMessage + @""" }]
                }]
            }";

            using var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, $"{apiUrl}?key={apiKey}");
            request.Content = new StringContent(requestBody, Encoding.UTF8);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                using JsonDocument doc = JsonDocument.Parse(responseBody);

                JsonElement root = doc.RootElement;

                var text = root
                    .GetProperty("candidates")[0]
                    .GetProperty("content")
                    .GetProperty("parts")[0]
                    .GetProperty("text")
                    .GetString();

                return text != null ? text : "No response";
            }
            else
            {
                return $"Error: {response.StatusCode} - {response.ReasonPhrase}";
            }
        }
    }
}

Here is the structure of the appsettings.json file. You must create your own key and replace it here for the example to work properly.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Gemini": {
    "ApiKey": "***************************************",
    "ApiUrl": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
  }
}

You can explore more in this example as per your requirements.

Thanks!

Happy Coding!!

ASP.NET Core 10.0 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.