Добавление веб DICOM-просмотрщика в ASP.NET Core приложение
В этом разделе
В этом руководстве показано, как создать пустое веб-приложение ASP.NET Core в Visual Studio .NET 2022 и добавить DICOM-просмотрщик в ASP.NET Core приложение.
Вот шаги, которые необходимо выполнить:
-
Создайте пустое ASP.NET Core приложение.
Откройте Visual Studio .NET 2022 и создайте новый проект типа "ASP.NET Core Web Application":
Настройте проект для использования .NET 8.0:
-
На стороне сервера: Добавьте ссылки на .NET-сборки Vintasoft в ваше ASP.NET Core приложение.
Скопируйте сборки Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Dicom.dll, Vintasoft.Shared.Web.dll, Vintasoft.Imaging.Web.Services.dll, Vintasoft.Imaging.Dicom.Web.Services.dll, Vintasoft.Imaging.AspNetCore.ApiControllers.dll и Vintasoft.Imaging.Dicom.AspNetCore.ApiControllers.dll из папки "<SdkInstallPath>\VintaSoft Imaging .NET 14.0\Bin\DotNet8\AnyCPU\" в папку "Bin" ASP.NET Core приложения и добавьте ссылки на .NET-сборки в ASP.NET Core приложение.
-
Серверная сторона: Укажите движок рисования, который должен использоваться VintaSoft Imaging .NET SDK для рисования 2D-графики.
Если ASP.NET Core приложение планируется использовать в среде Windows или Linux, рекомендуется применять графический движок SkiaSharp.
Если ASP.NET Core приложение будет использоваться только в среде Windows, можно применять как графический движок System.Drawing, так и SkiaSharp.
Вот шаги, которые необходимо выполнить для использования движка SkiaSharp:
-
Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Drawing.SkiaSharp.dll.
- Добавьте ссылку на nuget-пакет SkiaSharp версии 2.88.9.
- Откройте файл "Startup.cs" и добавьте строку кода "Vintasoft.Imaging.Drawing.SkiaSharp.SkiaSharpDrawingFactory.SetAsDefault();" в начало метода ConfigureServices - добавленный код указывает VintaSoft Imaging .NET SDK использовать библиотеку SkiaSharp для отрисовки 2D-графики.
Вот шаги, которые необходимо выполнить для использования движка System.Drawing:
-
Добавьте ссылку на .NET-сборку Vintasoft.Imaging.Gdi.dll.
- Откройте файл "Startup.cs" и добавьте строку кода "Vintasoft.Imaging.Drawing.Gdi.GdiGraphicsFactory.SetAsDefault();" в начало метода ConfigureServices - добавленный код указывает VintaSoft Imaging .NET SDK использовать библиотеку System.Drawing для отрисовки 2D-графики.
-
Серверная сторона: Создайте веб сервисы, которые позволяют загружать/скачивать файлы и просматривать DICOM-изображения.
- Добавьте в проект папку "Controllers".
-
Создайте веб сервис, позволяющий загружать/скачивать файл
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "Empty API controller", установите имя контроллера "MyVintasoftFileApiController" и нажмите кнопку "Add".
-
Укажите, что класс MyVintasoftFileApiController является производным от класса Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftFileApiController
Вот исходные коды класса MyVintasoftFileApiController:
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1.Controllers
{
public class MyVintasoftFileApiController : Vintasoft.Imaging.AspNetCore.ApiControllers.VintasoftFileApiController
{
public MyVintasoftFileApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Создайте веб сервис, позволяющий работать с DICOM-изображениями
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "Empty API controller", установите имя контроллера "MyVintasoftDicomApiController" и нажмите кнопку "Add".
-
Укажите, что класс MyVintasoftDicomApiController является производным от класса Vintasoft.Imaging.Dicom.AspNetCore.ApiControllers.VintasoftDicomApiController
Вот исходные коды класса MyVintasoftDicomApiController:
using Microsoft.AspNetCore.Hosting;
using Vintasoft.Imaging.Dicom.AspNetCore.ApiControllers;
namespace WebApplication1.Controllers
{
/// <summary>
/// A Web API controller that handles HTTP requests from clients and
/// allows to work with DICOM images.
/// </summary>
public class MyVintasoftDicomApiController : VintasoftDicomApiController
{
/// <summary>
/// Initializes a new instance of the <see cref="MyVintasoftDicomApiController"/> class.
/// </summary>
public MyVintasoftDicomApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Серверная сторона: Создайте MVC-контроллер для веб-представления, которое будет отображать DICOM-просмотрщик.
-
Нажмите правую кнопку мыши на папке "Controllers" и выберите меню "Add => Controller..." из контекстного меню
-
Выберите шаблон "MVC Controller - Empty", укажите имя контроллера "DefaultController" и нажмите кнопку "Add".
-
Откройте файл "Startup.cs" и добавьте контроллеры с представлениями в сервисы ASP.NET Core приложения:
Добавьте созданный MVC-контроллер в конечные точки ASP.NET Core приложения:
Включите обслуживание статических файлов для текущего пути запроса ASP.NET Core приложения:
Вот C# код файла Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Default}/{action=Index}/{id?}");
});
}
}
}
-
На стороне клиента: Добавьте JavaScript-библиотеки в проект.
-
Добавьте папку "wwwroot\js\" в ASP.NET Core приложение (если папка отсутствует).
- Скопируйте файлы Vintasoft.Shared.js, Vintasoft.Imaging.js, Vintasoft.Imaging.Dicom.js и Vintasoft.Imaging.Dicom.css из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Укажите, какие "стандартные" диалоги (показывать метаданные DICOM и т. д.) должны использоваться веб DICOM-просмотрщиком
-
Если веб DICOM-просмотрщик должен использовать готовые к использованию "стандартные" диалоговые окна Bootstrap:
- Добавьте библиотеки Bootstrap и jQuery в проект.
- Скопируйте файлы Vintasoft.Imaging.Dialogs.Bootstrap.js и Vintasoft.Imaging.Dicom.Dialogs.Bootstrap.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Если веб DICOM-просмотрщик должен использовать готовые к использованию "стандартные" диалоговые окна jQuery UI:
- добавьте библиотеки jQuery и jQuery UI в проект;
- Скопируйте файлы Vintasoft.Imaging.Dialogs.jQueryUI.js и Vintasoft.Imaging.Dicom.Dialogs.jQueryUI.js из папки "\VintaSoft Imaging .NET 14.0\Bin\JavaScript\" в папку "wwwroot\js\".
-
Если веб DICOM-просмотрщик должен использовать пользовательские "стандартные" диалоги, прочтите, как создать пользовательские "стандартные" диалоги
здесь
.
-
Клиентская сторона: Добавьте JavaScript-код, позволяющий отображать DICOM-изображения.
-
Создайте папку "wwwroot\UploadedImageFiles\SessionID" и скопируйте в нее тестовый файл DICOM "<SdkInstallPath>\VintaSoft\Imaging .NET 14.0\Examples\ASP.NET Core\CSharp\AspNetCoreImagingDemo\wwwroot\UploadedImageFiles\LossyJpeg_Monochrome2_000.0000.dcm". Этот файл будет отображаться в DICOM-просмотрщике.
-
Откройте веб-представление - файл "Views\Default\Index.cshtml".
-
Добавьте ссылки на используемые JavaScript-библиотеки:
-
Если вы используете диалоговые окна Bootstrap, добавьте ссылки на файлы Bootstrap и Vintasoft JavaScript-файлы.
Вот HTML-код, который добавляет ссылки на файлы Bootstrap и Vintasoft JavaScript-файлы:
<link rel="stylesheet" type="text/css" href="~/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.Dicom.css">
<script src="~/lib/bootstrap/dist/js/bootstrap.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dicom.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dicom.Dialogs.Bootstrap.js" type="text/javascript"></script>
-
Если вы используете диалоговые окна jQuery UI, добавьте ссылки на jQuery-файлы и Vintasoft JavaScript-файлы.
Вот HTML-код, который добавляет ссылки на jQuery-файлы и Vintasoft JavaScript-файлы:
<link rel="stylesheet" type="text/css" href="~/js/jquery-ui-css/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.css">
<link rel="stylesheet" type="text/css" href="~/js/Vintasoft.Imaging.Dicom.css">
<script src="~/js/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="~/js/jquery-ui.min.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Shared.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dicom.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dialogs.Bootstrap.js" type="text/javascript"></script>
<script src="~/js/Vintasoft.Imaging.Dicom.Dialogs.Bootstrap.js" type="text/javascript"></script>
-
Добавьте HTML-разметку (div-элемент, который будет отображать DICOM-просмотрщик) в веб-представление:
Вот код HTML-разметки:
<h1 style="text-align: center">VintaSoft DICOM Viewer Demo (ASP.NET Core)</h1>
<div id="dicomControlContainer" style="height: 800px"></div>
-
Добавьте JavaScript-код, который инициализирует и создает DICOM-просмотрщик:
Вот JavaScript-код, который инициализирует и отображает DICOM-просмотрщик:
<script type="text/javascript">
// set the session identifier
Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
// specify web services, which should be used by Vintasoft Web DICOM Viewer
Vintasoft.Shared.WebServiceJS.defaultFileService =
new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftFileApi");
Vintasoft.Shared.WebServiceJS.defaultDicomService =
new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftDicomApi");
// create DICOM control settings
var dicomControlSettings = new Vintasoft.Imaging.Dicom.WebDicomControlSettingsJS("dicomControlContainer", "dicomControl");
// create DICOM control
var dicomControl = new Vintasoft.Imaging.Dicom.WebDicomControlJS(dicomControlSettings);
// subscribe to the "warningOccured" event of DICOM control
Vintasoft.Shared.subscribeToEvent(dicomControl, "warningOccured", function (event, eventArgs) { alert(eventArgs.message); });
// add DICOM file "LossyJpeg_Monochrome2_000.0000.dcm" to the DICOM control
dicomControl.addFiles(["LossyJpeg_Monochrome2_000.0000.dcm"]);
</script>
-
Запустите веб-приложение ASP.NET Core и посмотрите результат.