我有一个基于Asp.net Core Web Api
项目的移动应用程序后端api。
我需要在同一个webapi项目中显示两个HTML
页面。是否可以在Web Api项目中放置HTML页面?
如果可以,怎么做?
我有一个基于Asp.net Core Web Api
项目的移动应用程序后端api。
我需要在同一个webapi项目中显示两个HTML
页面。是否可以在Web Api项目中放置HTML页面?
如果可以,怎么做?
在使用Web 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.在你的Web Api项目根目录下创建一个名为wwwroot
的文件夹,在wwwroot
文件夹中创建一个js文件夹。最后添加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;
}
Microsoft.AspNetCore.Mvc.Core
packageStartup.cs
in ConfigureServices
method, change services.AddControllers() to services.AddControllersWithViews();
Add new Controller like this:
[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
and ResetPassword.cshtml
to Views/Home
folder.