Building REST APIs using ASP.NET Core with Razor s

2019-07-25 15:19发布

问题:

As I was exploring the articles and contents on the internet about building REST APIs using asp.net core, I found out that razor web pages are not commonly used for front-end. Most of them are focused on Angular 1 && 2 for dealing with api data coming from the server (Ex: $http.get, $http.post). I was just wondering if there is any article that introduces how to use pure razor web pages as a front-end for dealing with web api or is there any ways to do it properly using .net core?

For ex:

[Route("api/students")]  
public class StudentsController : Controller
{
    private IStudentRepository _repository;

    public StudentsController(IStudentRepository repository)
    {
        _repository = repository;
    }

    [HttpGet("")]
    public IActionResult Get() 
    {           
        var results = _repository.GetAllStudents();

        return Ok(Mapper.Map<IEnumerable<StudentViewModel>>(results));
    }

And instead of using angular's $http service to render in view,

$http.get("/api/students")
    .then(function (response) {          
        ...
    }

is there any method to render api in razor view?

回答1:

You can use razor to call WebAPI but it's fairly pointless as you would miss out on all of the benefits of modern web development, eg you would have to postback to the server and reload the entire page instead of having an ajax request and just loading part of the page.

Essentially you would have to call your webapi from your MVC controller or some facade class within the controller, get the data response and then output that in a view using razor.

I'm not going to even bother posting code for this as you would be better off using Angular or some JS framework as you will end up with a better product.