I am new to Web API. I have written an ASP.NET Core Web API in VS 2022 to communicate with my SQL Server database.
This is my code:
using cd.Data;
using cd.ModelsCd;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace cd.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CdsController : ControllerBase
{
private readonly cdContext _context;
public CdsController(cdContext context)
{
_context = context;
}
// GET: api/Cds
[HttpGet]
public async Task<ActionResult<IEnumerable<Cd>>> GetCd()
{
return await _context.Cd.ToListAsync();
}
// GET: api/Cds/5
[HttpGet("{id}")]
public async Task<ActionResult<Cd>> GetCd(int id)
{
var cd = await _context.Cd.FindAsync(id);
if (cd == null)
{
return NotFound();
}
return cd;
}
}
The code I used to get info is:
static async Task LectureAsync2()
{
client.BaseAddress = new Uri("http://WebApiCd:7134/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// get 1 CD
Console.WriteLine("GET 1 Cd");
fich Cds1 = null;
HttpResponseMessage response = await client.GetAsync("http://webapicd:7134/api/Cds/11");
if (response.IsSuccessStatusCode)
{
Cds1 = await response.Content.ReadAsAsync<fich>();
}
Console.WriteLine(Cds1.CdNom);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
I have tried to use it with VS 2022 in a Windows console app => ok, in Windows .NET MAUI => ok, in VSD 2022 .NET MAUI Android emulator or Samsung s21 connected to my PC, the result is a .NET connection failure.
Network config is ok, because I have entered in the Samsung web browser http://webapicd:7134/api/Cds/11
and I get a good response.
Can you, please, indicate what I am doing wrong in Android?
Thanks in advance.
New contributor