20

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?

1 Answer 1

27

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is int not possible to just have the route be named implicitly without having to use the [Route] attribute?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.