Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http 404 when retrieving data after an ajax post (using web api)

i am getting started with asp.net, ajax/jquery and web api.

I wrote a really basic web app just to learn what's going on:

Here the model:

public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
}

Here 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 a get function 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 a GET after a successful POST call. Let's say i have triggered the post method and the controller successfully add a new Author like {"Id":"3", "Name":"Tom", "Surname":"Cruise"} to the authors List (and i am checking this logging on the console details of each author of the list in the Post method of the controller). Now if i try a GET like 'api/authors/3' i got an HTTP 404, while a GET with uri 'api/authors/1' or 'api/authors/2' give an HTTP 200. Could anyone explain me why the server gives me a 404 when trying to retrieve data added with a successful POST?

like image 640
spinlud Avatar asked Jul 10 '26 14:07

spinlud


1 Answers

An controller is instantiated for each request.

You need to ensure that same authors instance is shared across all controller instances by making the authors field static like so:

static List<Author> authors = new List<Author> 
{
    new Author {Id=1, Name="Alan", Surname="Timo" },
    new Author {Id=2, Name="Jack", Surname="Russel"}
};
like image 83
User 12345678 Avatar answered Jul 12 '26 07:07

User 12345678



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!