I have a .net 7 web api where I’m trying to validate addresses. I believe I have all the models correct even the response body. I’m unable to get any kind of response back. It works on postman but I cannot get it to work using my api. Can someone please tell me what I’m doing wrong? I’ve even tried asking chatgpt but to no prevail.
(yes I have everything set up from google maps, like I said it works just fine on postman)
Here is the link to the api:
https://developers.google.com/maps/documentation/address-validation/requests-validate-address
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValidateAddressController : ControllerBase
{
private readonly ILogger<ValidateAddressController> _logger;
private readonly HttpClient _httpClient;
public ValidateAddressController(ILogger<ValidateAddressController> logger, HttpClient httpClient)
{
_logger = logger;
_httpClient = httpClient;
}
public class AddressValidationRequest
{
public Address? Address { get; set; }
}
public class Address
{
public string? RegionCode { get; set; }
public string[]? AddressLines { get; set; }
}
public class AddressValidationResponse
{
public string FormattedAddress { get; set; }
public string AddressType { get; set; }
public bool Valid { get; set; }
// Add other response fields as needed
}
[HttpPost("GetFormattedAddress")]
public async Task<IActionResult> ValidateAddress([FromBody] AddressValidationRequest request)
{
if (request?.Address == null)
{
_logger.LogWarning("Request or Address is null");
return BadRequest("Request or Address cannot be null");
}
var requestUri = $"https://addressvalidation.googleapis.com/v1:validateAddress?key=<MY api key>";
try
{
_logger.LogInformation("Sending request to Google Maps API");
var response = await _httpClient.PostAsJsonAsync(requestUri, request);
if (response.IsSuccessStatusCode)
{
var addressValidationResponse = await response.Content.ReadFromJsonAsync<AddressValidationResponse>();
if (addressValidationResponse == null)
{
_logger.LogError("Response content is null");
return StatusCode(500, "Response content is null");
}
_logger.LogInformation("Successfully received response from Google Maps API");
return Ok(addressValidationResponse);
}
else
{
var errorResponse = await response.Content.ReadAsStringAsync();
_logger.LogError($"Google Maps API error: {response.StatusCode} - {errorResponse}");
return StatusCode((int)response.StatusCode, errorResponse);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while validating address");
return StatusCode(500, "Internal server error");
}
}
}
Response from Swagger
enter image description here
Request Body
enter image description here
I’ve tried updating the models, using the two different types of body models, and it just doesn’t seem to want to work with my code.