In my ASP.NET Core MVC web app project, I'm sending a POST request to an external API using HttpClient. Everything seems to be working correctly, but on the JavaScript side, the response is undefined. There are no error messages either.
Controller:
[HttpPost]
public async Task<Kullanici> KullaniciKayit(Kullanici model)
{
var result = await _kullaniciService.KullaniciKayit(model);
return Ok(result); // Bu satır var
}
My Ajax request:
$.ajax({
url: "/Home/KullaniciKayit",
type: "POST",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) {
console.log("Gelen veri:", data); // <-- burada 'undefined' geliyor
alert("Kayıt başarılı");
},
error: function (xhr) {
console.error("Hata:", xhr.responseText);
}
});
My micro service:
public async Task<Kullanici> KullaniciKayit(Kullanici model)
{
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/KullaniciKaydet/KullaniciKayit", content);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Kullanici>(responseBody);
}
else
{
throw new HttpRequestException($"API Error: {response.StatusCode}");
}
}
Web app: I'm sending an Ajax request from a form to the KullaniciKayit action in the HomeController. This action calls the API via a service layer.
API: the endpoint https://localhost:44397/api/KullaniciKaydet/KullaniciKayit is working properly.
The Kullanici model is shared between both the web app and the API.
What I've checked:
- The API was tested via Postman → it returns the correct data
- The web app controller includes return
Ok(...) - The API returns
Content-Type: application/json - In the browser's Network tab, the request is successful but the response body is
{} console.log(data)showsundefined
What could be the issue?
the response body is {}...what did you expect it to be, and why? That's potentially a valid response. Have you checked whatvar responseBodyin the C# code contained, while debugging your C#?public async Task<Kullanici>topublic async Task<IActionResult>success: function (data, status, xhr) { console.log("Status:", status); console.log("Raw Response:", xhr.responseText); console.log("Parsed Data:", data); }OkResult<>type in yourKullaniciKayitAPI action which expects the return value withTask<Kullanici>.https://localhost:44397/api/KullaniciKaydet/KullaniciKayitdirectly from the AJAX code? Your ASP.NET doesn't add any value to the call - it just passes it on and returns the value. Doesn't add or remove or transform data, doesn't handle any extra authentication, or anything else useful. Why not remove the middleman? If you get CORS issues you can solve that in the API code