Перед использованием html с веб-API, вам необходимо настроить:
1.Startup.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();
}
2.Создать папку wwwroot
в вашем веб-API проект root и создание папки js внутри папки wwwroot
. Наконец добавьте Index.html
:

Вот рабочий демо о Web Api с Html страницей:
1.Модель:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
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;
}
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>
4.site. 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;
}
Ссылка: Вызов ASP. NET Базовый веб-API с JavaScript