How do I return information from an API? C#

0

I've made a simple API to interface with a SQL server and I have been able to use Postman and my web browser to access it, but when I go to access it from a console application, I am unable to do so. All I want to do in the API is to check if a username is located in a database and if it is, return true. I've tried putting the BaseAddress inside of the GetAsync() Function, to no avail, as well as removing and re-adding the Client.DefaultRequestHeaders.

API:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace Moving_App_Web_API.Controllers
{
    [Route("MovingApp/Users")]
    [ApiController]

    public class MovingAppController : ControllerBase
    {
        List<string> Username;

        private readonly ILogger<MovingAppController> _logger;
        public MovingAppController(ILogger<MovingAppController> logger)
        {
            _logger = logger;
            Username = new List<string>();
        }

        [HttpGet]
        public string GetMovingApp()
        {
           return "Hello World";
        }
        
        [HttpGet("{username}")]
        public string UserCheck(string username)
        {
            bool UsernameExist;

            ServerConnection Connection = new ServerConnection();
            SqlConnection conn = new SqlConnection(Connection.connString);

            conn.Open();

            SqlCommand cmd = new SqlCommand("SELECT Count(UserID) FROM Users WHERE Username = @Username", conn);
            cmd.Parameters.AddWithValue("@Username", username);

            int count = Convert.ToInt32(cmd.ExecuteScalar());

            if (count != 0) UsernameExist = true;
            else UsernameExist = false;

            /*SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            foreach(DataRow dr in ds.Tables[0].Rows)
            {
                Username.Add((string)dr["Username"]);
            }*/
            conn.Close();
            return UsernameExist.ToString();
        }

Console App:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
           CallWebAPIAsync();
        }

        static void CallWebAPIAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:44340/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                
                string response = client.GetStringAsync("http://localhost:44340/MovingApp/Users/User1").Result;
                if (response != null)
                {
                    Console.WriteLine("IT WORKS");
                }
            }
        }
    }
}

The errors I get when I run the ConsoleApp are:

  HResult=0x80131500
  Message=One or more errors occurred. (An error occurred while sending the request.)
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at ConsoleApp3.Program.CallWebAPIAsync() in C:\Users\Computer\source\repos\ConsoleApp3\ConsoleApp3\Program.cs:line 23
   at ConsoleApp3.Program.Main(String[] args) in C:\Users\Computer\source\repos\ConsoleApp3\ConsoleApp3\Program.cs:line 12

Inner Exception 1:
HttpRequestException: An error occurred while sending the request.

Inner Exception 2:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..

Inner Exception 3:
SocketException: An existing connection was forcibly closed by the remote host.
c#
http
asp.net-web-api
asked on Stack Overflow May 11, 2021 by JonTheBrownDog

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0