[英]ASP.NET Core WebAPI 404 error
I create a Web Api in asp.net core this the content of Api: 我在asp.net核心创建一个Web Api这个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. 正如我在ASp.net核心(WebApi模板)中所知,我们不需要任何配置,如注册路由,我们需要在Asp.net Mvc 5.3及更早版本。
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? 因此,当我尝试通过浏览器或邮递员调用
GetAllBlog
,通过此URL http://localhost:14742/api/Blog/GetAllBlog
,它得到404 error
,有什么问题?
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. 您已经在控制器类的顶部包含了api / [controller]路由,因此在定义访问方法的路径时不需要再次包含它。 In essence, change the Route to api/Blog/GetAllBlog to GetAllBlog.
实质上,将Route to api / Blog / GetAllBlog更改为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.
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.