Asp. net core web api show page - PullRequest
       1

Asp. net core web api show page

0 голосов
/ 22 февраля 2020

У меня есть бэкэнд API для моего мобильного приложения в проекте Asp.net Core web Api.

Мне нужно будет показать две HTML страницы в одном проекте webapi. Возможно ли иметь HTML страниц в проекте web api? И если да, то как?

Ответы [ 2 ]

0 голосов
/ 24 февраля 2020

Перед использованием 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:

enter image description here

Вот рабочий демо о 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

0 голосов
/ 22 февраля 2020

Да, вы можете сделать это.

Шаги, например, для проекта Api Core:

  1. Установка Microsoft.AspNetCore.Mvc.Core пакета
  2. В Startup.cs в ConfigureServices методе, измените services.AddControllers () в services.AddControllersWithViews();
  3. Добавьте новый контроллер, например, так:

    [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");
        }
    }
    
  4. Добавьте ваши просмотры DownloadApp.cshtml и ResetPassword.cshtml в Views/Home папку.

Теперь вы можете просматривать свою страницу по следующим URL: Default / ResetPassword и Default / DownloadApp

...