Http 404 when getting data after ajax post (using web api)
I am getting started with asp.net, ajax / jquery and web api.
I wrote a really basic web application to see what's going on:
Here's the model:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
Here's the controller:
public class AuthorsController : ApiController
{
List<Author> authors = new List<Author>
{
new Author {Id=1, Name="Alan", Surname="Timo" },
new Author {Id=2, Name="Jack", Surname="Russel"}
};
[HttpGet]
public IHttpActionResult GetAuthor(int id)
{
Author autore = authors.FirstOrDefault(p => p.Id == id);
if (autore == null)
return NotFound();
else
return Ok(autore);
}
[HttpPost]
public Author PostAutore([FromBody] Author author)
{
authors.Add(author);
foreach (Author aut in authors)
{
Debug.WriteLine(aut.Id + " " + aut.Name + " " + aut.Surname);
}
return author;
}
}
Here's the get and post function in jquery:
function GetAuthorById() {
var id = $('#authorID').val();
$.getJSON('api/authors/' + id).done(function (data) {
alert(data.Name + data.Surname);
});
}
function PostAuthor() {
var author = {
Id: $('#newAuthorId').val(),
Name: $('#newAuthorName').val(),
Surname: $('#newAuthorSurname').val()
};
$.post(
'api/authors',
author,
function (data) {
alert(data.Name + data.Surname);
}
);
}
My question is about using GET after a successful POST call. Let's say I called the post method, and the controller successfully adds a new Author like {"Id": "3", "Name": "Tom", "Surname": "Cruise"} to the author list (and I'm checking this logging to the console details of each list author in the controller's Mail method). Now if I try a GET like api / authors / 3 I get HTTP 404 and GET with uri 'api / authors / 1' or 'api / authors / 2' gives HTTP 200. Can anyone explain to me why is the server giving me 404 when trying to get data appended with a successful POST?
source to share
A controller is created for every request.
You need to make sure the same instance is authors
used for all controller instances by creating the field authors
static
like this:
static List<Author> authors = new List<Author>
{
new Author {Id=1, Name="Alan", Surname="Timo" },
new Author {Id=2, Name="Jack", Surname="Russel"}
};
source to share