Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core WebAPI 404 error

I create a Web Api in asp.net core this the content of Api:

 [Route("api/[controller]")]
public class BlogController : Controller
{

    public IContext _context { get; set; }
    public BlogController(IContext ctx)
    {
        _context = ctx;
    }

    [HttpGet]
    [Route("api/Blog/GetAllBlog")]
    public List<Blog> GetAllBlog()
    {
        return _context.Blogs.ToList();
    }


   }

as i know in ASp.net Core (WebApi Template) we don't need any configuration like registration Route, which we need in Asp.net Mvc 5.3 and older.

So when i try to call the GetAllBlog by browser or Postman, by this url http://localhost:14742/api/Blog/GetAllBlog , it gets me 404 error, what is problem?

like image 912
pejman Avatar asked Jan 02 '17 06:01

pejman


1 Answers

You have already included the api/[controller] route at the top of the controller class so you don't need to include it again while defining route for accessing method. In essence, change the Route to api/Blog/GetAllBlog to GetAllBlog. Your code should look like this:

[Route("api/[controller]")]
public class BlogController : Controller
{

    public IContext _context { get; set; }
    public BlogController(IContext ctx)
    {
        _context = ctx;
    }

    [HttpGet]
    [Route("GetAllBlog")]
    public List<Blog> GetAllBlog()
    {
        return _context.Blogs.ToList();
    }

    [HttpGet]
    [Route("GetOldBlogs")]
    public List<Blog> GetOldBlogs()
    {
        return _context.Blogs.Where(x => x.CreationDate <= DateTime.Now.AddYears(-2)).ToList();
    }
}

You also need to have different route names for methods. Hope this helps.

like image 60
Dronacharya Avatar answered Oct 05 '22 01:10

Dronacharya