pmn
pmn

Reputation: 2255

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?

Upvotes: 20

Views: 36106

Answers (1)

Dronacharya
Dronacharya

Reputation: 1281

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.

Upvotes: 27

Related Questions