使用具有Razor语法的ASP.NET Core构建REST API [英] Building REST APIs using ASP.NET Core with Razor syntax

查看:241
本文介绍了使用具有Razor语法的ASP.NET Core构建REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览Internet上有关使用asp.net core构建REST API的文章和内容时,我发现剃须刀的网页通常不用于前端.他们大多数都专注于Angular 1&& 2用于处理来自服务器的api数据(例如:$ http.get,$ http.post).我只是想知道是否有文章介绍如何使用纯剃刀网页作为处理Web API的前端,或者是否有任何方法可以使用.net core正确地做到这一点?

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?

例如:

[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));
    }

而不是使用angular的$ http服务在视图中呈现,

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

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

是否有任何方法可以在razor视图中呈现api?

is there any method to render api in razor view?

推荐答案

您可以使用razor调用WebAPI,但这是毫无意义的,因为您会错过现代Web开发的所有好处,例如,您必须回发到服务器并重新加载整个页面,而不是发出ajax请求,而只是加载页面的一部分.

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.

基本上,您必须从MVC控制器或控制器中的某些Facade类调用webapi,获取数据响应,然后使用剃刀在视图中输出.

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.

我什至不打算为此发布代码,因为使用Angular或某些JS框架会更好,因为最终会得到更好的产品.

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.

这篇关于使用具有Razor语法的ASP.NET Core构建REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆