Asp.net core web api显示页面

dal*_*on5 4 c# api asp.net-core-webapi

我的项目中有一个用于我的移动应用程序的后端 API Asp.net Core web Api

我需要HTML在同一个 webapi 项目中显示两个页面。web api项目中可以有HTML页面吗?如果是的话怎么办?

Ren*_*ena 11

在使用 html 和 web api 之前,您需要配置:

1.启动.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    //Configure the app to serve static files and enable default file mapping. 
    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseHttpsRedirection();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

2.wwwroot在Web Api项目根目录中创建一个文件夹,并在该文件夹内创建一个js文件夹。最后wwwroot添加Index.html

在此输入图像描述

这是一个关于带有 Html 页面的 Web Api 的工作演示:

1.型号:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

2.控制器:

[Route("api/[controller]")]
[ApiController]
public class TestsController : ControllerBase
{
    // GET: api/Tests
    [HttpGet]
    public IEnumerable<Test> GetTest()
    {
        var model = new List<Test>() { 
        new Test(){Id=1,Name="aaa"},
        new Test(){Id=2,Name="bbb"}
        };
        return model;
    }
Run Code Online (Sandbox Code Playgroud)

3.HTML:

<!DOCTYPE html>
<html>
<body>
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
        <tbody id="todos"></tbody>
    </table>

    <script src="/js/site.js" asp-append-version="true"></script>
    <script type="text/javascript">
        getItems();
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

4.网站.js:

const uri = 'api/Tests';
let todos = [];

function getItems() {
    fetch(uri)
        .then(response => response.json())
        .then(data => _displayItems(data))
        .catch(error => console.error('Unable to get items.', error));
}
function _displayItems(data) {
    const tBody = document.getElementById('todos');
    tBody.innerHTML = '';
    data.forEach(item => {
        let tr = tBody.insertRow();
        let td1 = tr.insertCell(0);
        let textNode1 = document.createTextNode(item.id);
        td1.appendChild(textNode1);

        let td2 = tr.insertCell(1);
        let textNode2 = document.createTextNode(item.name);
        td2.appendChild(textNode2);


    });

    todos = data;
}
Run Code Online (Sandbox Code Playgroud)

参考: 使用 JavaScript 调用 ASP.NET Core Web API