447 questions
the catch path in the try/catch must either throw an error (no return) or return a value.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
I am trying to create my first API in .NET as you can see below.
But I am getting this error:
'WeatherForecastController.Get()': not all code paths return a value (CS0161) (MyTempAPI)
using System.Data;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
namespace MyTempAPI.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
List<CountryData> web;
private SqlDataAdapter _adapter;
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetCountry")]
public IEnumerable<CountryData> Get()
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "xxxxxxxxx.database.windows.net";
builder.UserID = "xxxxxx";
builder.Password = "xxxxxxxxx";
builder.InitialCatalog = "xxxxx";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
// List<CountryData> data = JsonSerializer.Deserialize<List<CountryData>>(result);
String sql = "SELECT country_code, country_name_en AS country_name FROM dbo.country";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
DataTable _dt = new DataTable();
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
web = new List<CountryData>();
while (reader.Read())
{
web.Add(new CountryData()
{
country_code = reader.GetString(0),
country_name = reader.GetString(1)
});
}
}
}
}
return web;
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
}
the catch path in the try/catch must either throw an error (no return) or return a value.