[英]Asp.net core web api show page
我的移动应用程序在Asp.net Core web Api
项目上有一个后端 api。
我需要在同一个 webapi 项目中显示两个HTML
页面。 web api 项目中是否可以有 HTML 页? 如果是的话怎么办?
在使用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();
}
2.在您的 Web Api 项目根目录中创建一个wwwroot
文件夹,并在wwwroot
文件夹中创建一个 js 文件夹。最后添加Index.html
:
这是一个关于 Web Api 和 Html 页面的工作演示:
1.Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
2.Controller:
[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.网站.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;
}
是的,你可以这样做。
Api 核心项目的步骤示例:
Microsoft.AspNetCore.Mvc.Core
packageStartup.cs
中的ConfigureServices
方法中,将 services.AddControllers() 更改为services.AddControllersWithViews();
像这样添加新的 Controller:
[Route("Default")] public class HomeController: Controller { [Route("DownloadApp")] public IActionResult DownloadApp() { //you code here return View(); } [Route("ResetPassword")] public IActionResult ResetPassword() { //you code here return View("Index"); } }
DownloadApp.cshtml
和ResetPassword.cshtml
添加到Views/Home
文件夹。现在您可以通过以下网址查看您的页面:Default/ResetPassword 和 Default/DownloadApp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.