Как запустить net core приложение на линукс

от admin

Creating your first .NET Core project on Linux

This post is the first of a series in which we’ll discuss about the experience of developing and running .NET web applications in Linux environments.

Introduction to .NET Core

.NET Core is an opensource, multiplatform version the .NET Framework which is officially supported and maintained by Microsoft.

This post will give an overview of how to run a .NET Core web project in Ubuntu, starting with its basic architecture and ending in the configuration of Kestrel for creating a web application.

.NET Core framework already provides scaffolding tools for bootstrapping your projects, but this time we’ll develop this from scratch starting from a basic console application.

Installing .NET Core on Linux

We’ll install .NET Core in Ubuntu, following Microsoft’s official website, but you can find installation instructions for most common distros. As a development IDE you can use any text editor, but we are going to use Visual Studio Code which, in my opinion, offers the best integration.

Creating my first “Hello world” in C # .NET Core

From the command console run these commands:

  • dotnet new console (to create a console project in .NET Core)
  • dotnet restore (to restore packages and project dependencies)
  • dotnet run (to execute our code).

Configuring Kestrel

Kestrel is a multi-platform web server used to host .NET Core web applications.

To add Kestrel to our project we must add the it’s dependencies to the .csproj file as follows:

Now we will open our Program.cs file and in it’s Main method replace the following lines:

For these lines:

In order to use Kestrel and the HTTP context we will have to add these references:

Now we need to add the Startup.cs .

Using Startup.cs

With the file Startup.cs we are going to configure for the project host.

By now our Startup.cs should be looking something like this:

The Configure method is called at runtime and it is used to configure and channel HTTP requests.

IApplicationBuilder provides the mechanisms for configuring application requests. The middleware is also configured here.

Next, we will configure the app to use IIS/IIS Express for the web server and set the content root. To do this we will add the following lines before the Build() in Program.cs :

To use IIS with ASP.NET Core, both UseKestrel and UseIISIntegration must be specified. Kestrel is designed to run behind a proxy and should not be deployed without it.

Now let’s add the IIS package reference in .csproj , and run dotnet restore for updating dependencies.

We will add “Watcher” to see the changes reflected without needing to stop and re-run the project. For that we are going to add the following dependency:

As always we will have to run dotnet restore , and now if we run dotnet watch run we should be able to see our changes being reflected without us having to reload out application.

Congratulations!

You already have your .Net Core application running on Linux and you learned how to configure it from scratch using Kestrel and develop it in a web environment. In the next post, I explain how to build an MVC architecture application using the tools provided by .Net Core.

Install .NET Core Apps on Linux in 5 Minutes

As a big fan of open source, I’m loving the fact that .NET Core is cross-platform. It opens up endless possibilities, from hobby projects, experiments, and proofs of concept, to massive high-load production applications that run on cost-effective infrastructure with high security and scalability. I usually get the simplest and cheapest $5/month Ubuntu-based virtual private server (VPS) from any cloud platform provider instead of the more complex and expensive container instances or cloud computing services.

I’m going to guide you through the steps on how to set up a .NET Core runtime environment, and how to deploy a .NET Core web application with Okta authentication, once you’ve got an Ubuntu VPS, all using nothing more than the Terminal.

The Benefits of Using Okta

Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Using Okta, you don’t have to worry about implementing sign up, login and logout flows manually. In our sample app, we will set up Okta to handle our user management for OAuth sign-in. There are a few tricks to set up .NET Core to work on Linux (especially when it comes to containerization on a host like AWS or Azure), but don’t worry — you will get a good overview in this tutorial.

Prerequisites

Install .NET Core SDK/Runtime on Linux

.NET Core SDK or Runtime: Which One Is Best

The .NET Core runtime allows you to run applications on Linux that were made with .NET Core but didn’t include the runtime. With the SDK you can run but also develop and build .NET Core applications. Normally you would need only the runtime in a production environment and the SDK in a development environment.

Today we are going to build and run our sample application on the same machine. So let’s install the .NET Core SDK.

Adding the Package Repository

We need to add Microsoft’s package signing key to make the package repository trusted by the system.

Open Terminal and run the following commands:

Installing the SDK

To make sure the installation was successful, run:

The output should be the installed .NET Core version.

Building and Running a .NET Core application on Linux

We are going to use the .NET Core CLI to build and run the sample application.

Copying the source code

I have prepared a sample application for the sake of this example. Let’s use git to copy it to our machine from GitHub.

Building the .NET Core Application

Enter the folder where we just copied the source code:

The first build might take a while. Then the output should be something like:

Running the .NET Core Application

To run the application in Development mode, type:

Running the sample application will fail because we need to set up Okta login first.

Quickly Set Up Okta Login

Navigate to Applications , then select Add Application .

Select Web as a platform:

On the next screen add the following: Login redirect URIs: https://localhost:5001/authorization-code/callback

Logout redirect URIs: https://localhost:5001/signout/callback

When finished, click Done.

Take note of your client credentials ( Client ID and Client secret).

Open appsettings.json in your favorite code editor and add your credentials.

You can find your Org URL in the top right corner of the Dashboard:

Now the sample app is ready to run:

You can now open a browser window at http://localhost:5000 to see the application running. Also you can try logging with Okta in the top right corner.

Troubleshooting

In case you run into a Correlation Error after logging in with Okta, you need to manually set the SameSite cookie attribute to None , and enable SSL (HTTPS) on your server. Check out more about how SameSite affects your apps in this article.

Takeaways

Developing .NET Core applications on Linux is not the stuff of science fiction any more. Since Microsoft started moving away from closed-source and platform-dependent solutions, a Linux-based development environment has its advantages. I believe tools like VSCode and Rider—also available on every platform—are mature enough to make them reasonable competitors of the classic Visual Studio IDE for Windows. I’ve successfully used Linux as my primary development environment for .NET Core for a few years now. Give it a try yourself and let us know what your experience has been in the comments below!

Learn More About .NET and Okta

If you are interested in learning more about security and .NET check out these other great articles:

Don’t forget to follow us on Twitter and subscribe to our YouTube channel for more great tutorials.

ASP.NET Core: ваше первое приложение на Linux c использованием Visual Studio Code

Решил недавно написать небольшое ASP.Net MVC приложение после многолетнего перерыва и знающие люди на Хабре подсказали попробовать новый ASP.Net Core, тем более, что он работает в Линуксе из коробки без необходимости задействовать mono, и, судя по последним тестам, даже показывает неплохую производительность. За основу взял аналогичную статью для Mac, однако здесь в отличии от вдохновившей меня статьи хочу описать процесс пошагово в одном месте, для того, чтобы не пришлось лазить по перекрёстным ссылкам, пытаясь разобраться как установить непонятно для чего предназначенные приложения и пакеты. Такое подробное описание процесса возможно поможет многим избежать граблей, с которыми пришлось столкнуться мне. Несколько фраз и рисунков, в части одинаковой для любой платформы, с правками и корректировками взяты из статьи для Mac.

Установка .Net Core и Visual Studio Code

Приводимые здесь команды установки подходят для дистрибутивов Ubuntu 16.04/Mint 18.x, для остальных можно найти здесь.

Установка .Net Core:

Устанавливаем новейший на данный момент RC4 для совместимости с новейшим генератором проектов aspnet:

Установка Visual Studio Code

Устанавливается легко в пару кликов по этой ссылке.

Установка расширения C#

Запускаем Visual Studio Code, нажимаем Ctrl-P, вводим команду:
ext install csharp

В появившейся слева панели нажимаем «Установить» напротив соответствующего расширения, если это не произошло автоматически. Visual Studio Code можно пока закрыть.

Подготовка среды разработки и формирование шаблонов приложений

Устанавливаем новейший node.js с оригинального сайта (тот, что идёт с дистрибутивом не подходит), он нам нужен из-за менеджера пакетов npm, который идёт вместе с ним:
Для других дистрибутивов инструкция здесь.

Инициализация проекта

Для инициализации используется скаффолдер Yeoman — инициализатор проекта, включающий в себя развёртывание файловой структуры и генерацию шаблона проекта, т.е. исходного кода приложения. Включает в себя скаффолдер Yo, менеджер пакетов Bower и менеджер задач Grunt. При установке Yo вам будут установлены также Bower и Grunt. Здесь устанавливаем в любом терминале также новейший генератор aspnet, в котором возвращена система сборки msbuild вместо project.json:

Запуск генератора проекта

  • Выбираем пункт Web Application Basic [without Membership and Authorization] и нажимаем Enter
  • Выбираем Bootstrap (3.3.6) в качестве фреймворка UI и нажимаем Enter
  • Оставляем имя «WebApplicationBasic» в качестве имени приложения и нажимаем Enter
  • Установка: npm install -g generator-aspnetpostgresql
  • Генерация шаблона: yo aspnetpostgresql

Восстановить и собрать можно, а вот запускать пока рано: нужно ещё кое что сделать.

Разработка приложений ASP.NET Core MVC на Linux с помощью Visual Studio Code

Теперь запустите Visual Studio Code.
image
Выберите пункт Файл → Отрыть папку и выберите папку, в которой Вы создали шаблон приложения ASP.NET Core MVC с помощью yo.

При первом запуске Visual Studio Code выдаст предупреждение об отсутствии необходимых инструментов для сборки и отладки. Нажимаем Yes , чтобы добавить их. Без этого автоматическая отладка и сборка средствами Visual Studio Code будет недоступна, а только через терминал командами dotnet build и dotnet run .

В Терминале Visual Studio Code (Ctrl-`) выполните команду dotnet restore , чтобы восстановить зависимости проекта (если не сделали этого раньше). Другой способ — выполнить команду Ctrl-Shift-P в Visual Studio Code и затем ввести dot, как показано ниже (у меня почему-то не заработало):

image

Для тех, кто только приступает к использованию Visual Studio Code (или Code, для краткости), следует заметить, что данный продукт не только имеет удобный, простой и отзывчивый интерфейс, обеспечивающий быструю работу с файлами, но он также предоставляет инструменты для наиболее эффективного написания кода.

  • Explore
  • Search
  • Git
  • Debug
  • Extensions

Code интегрируется с Git, если он установлен на вашем компьютере. При помощи Git viewlet можно создавать новые репозитории, подтверждать изменение кода, отправлять изменения.

image

Debug viewlet поддерживает интерактивную отладку приложений.

Кроме того, в редакторе Code есть множество замечательных функций. Вы увидите, что неиспользованные операторы using будут подчеркнуты и могут быть удалены автоматически при помощи Сtrl-. , если значок лампочки отображается на экране. Также можно видеть, сколько ссылок на классы и методы есть в проекте. Если вы переходить с Visual Studio, то вы можете использовать многие знакомые сочетания клавиш, например, Сtrl-K+C , чтобы закомментировать блок кода или Ctrl-K-U , чтобы раскомментировать его.

Запуск приложения при помощи Kestrel

  • Установив .Net Core Project Manager (Nuget) через viewlet Extensions (Расширения): Ctrl-Shift-P , набираем Nuget , ↵, затем Kestrel ↵ выбираем Microsoft.AspNetCore.Server.Kestrel
  • Через командную строку в терминале редактора vs code editor:
Читать:
Где хранится профиль google chrome

Всё, теперь можно запускать: нажимаем F5 или в терминале dotnet run , при этом автоматически запускается браузер с приложением по адресу: localhost:5000 . Чтобы остановить веб-сервер, нажмите Ctrl+C. Вот и всё, можете наслаждаться вашим первым приложением ASP.Net Core:
image

A developers guide to running WPF apps on Linux with .NET Core and Wine

I have worked on several large WPF applications that took many years to create. When we started development, our users only used Windows, which made WPF a natural choice. WPF provides a modern UI and workflow that ran on all versions of Windows. Today, our customers increasingly want to use our applications on Linux, so we have been looking for a way to achieve this at an investment level that makes sense given the current size of the user base. With this shift, we are also looking to maximize the investments we have already made with our WPF applications. To move to Linux, we considered several options:

  • Update the architecture of the applications to make the WPF-specific code as small as possible, and enable a per-platform UI. We could continue to use WPF on Windows and choose something else for Linux.
  • Switch to a cross-platform UI stack. With libraries like QT, we could create an app that would work cross-platform.
  • Switch to a HTML-based UI stack. We could rearchitect our application to be an Electron app. Much of the non-UI code could be reused, but we would have to recreate the UI from scratch in HTML / JavaScript and update our architecture to support interop between JavaScript and our existing C# code.
  • Switch to some sort of cloud-hosted application. Platforms like Amazon App Stream enable hosting of existing Windows apps and enable use from any platform.

After some evaluation, we were not happy with any of these solutions. They were either cost prohibitive or would have resulted in a less desirable application. Given the size of the Linux customer base, we needed a solution that is initially low cost, and provided a model that could evolve to support tailoring features to each platform as the user base grows. We found the solution to these problems with Wine.

With .NET Core 3.0’s support for WPF, a WPF application can run on Linux under Wine. Wine is a compatibility layer which allows Windows applications on Linux and other OSes, include .NET Core Windows applications. More information about Wine is available at the WineHQ website.

Wine is often used to enable users to run games on Linux. In order to support gaming, the Wine team invested in providing a full-featured implementation of DirectX. This is great for WPF, since it uses DirectX for rendering, and, from the rendering perspective, is a lot like a DirectX game.

Wine is typically used to run applications out of the box. This is a high bar, since any missing API or behavioral difference between Wine and Windows can result in an unusable app. If you are willing to thoroughly test and make necessary application changes, you can be successful running your WPF apps on Linux. I’ve had great success getting several applications, including some very large WPF apps, running on Linux with minimal changes.

Getting started

Port to .NET Core

In theory, a .NET Framework WPF application could be updated to run on Linux with Wine. However, .NET Framework’s license prohibits use on any platform other than Windows. .NET Core is open source and cross-platform. .NET Core is also where Microsoft is putting their .NET investment, so porting to .NET Core is a good idea even for Windows-only use. Given the issues with .NET Framework, the first step towards Linux support is to port your application to .NET Core. There are many great documents available on how to port a WPF application to .NET Core. Microsoft’s Migration page is a great place to start.

It’s much easier to debug and fix issues on Windows than on Linux, so make sure your application is working well on Windows before you try it on Linux.

Install Wine

.NET Core WPF Apps work well with current versions of Wine, but you may run into issues with older versions. I have been testing my apps with Wine 4.21.

Follow the instructions on the Wine Installation page to install a Wine package that is compatible with your Linux distribution. I’ve had success installing the development build available from WineHQ directly. Once Wine is installed, you need to set it up. Running winecfg is an easy way to get Wine to setup the Wine prefix (configuration) directory.

When setting up the Wine prefix directory, Wine will prompt you to install Mono. You do not need to install Mono .NET to run .NET Core applications, so you can cancel the install of Wine Mono. Wine Gecko is also not needed.

Once wineconfig is running, there should be a .wine directory in your home directory:

Nothing needs to be changed in WineConfig so it can be closed.

Setup .NET Core on Wine

The easiest way to install .NET Core for testing is to copy the dotnet directory from your Windows install to the Linux computer.

Copy the entire dotnet folder from the Program Files directory on Windows:

to the Program Files directory in the Wine configuration location:

Install / copy your application to Linux

Applications that can run from the build output directory can be copied from Windows to anywhere on your Linux machine. I usually copy the application into my home directory for testing. Wine also supports setting registry keys or environment variables. If your required setup has more complex requirements, you may have more difficulty, but Wine supports a surprising number of Windows features.

Make sure fonts are available

When testing out various applications, I often experienced odd crashes when an appropriate font was not available. For testing purposes, the easiest way to get necessary fonts is with Winetricks. Install and run Winetricks. From there, you can install fonts available from a variety of sources.

Run your application under Wine

Once your app is copied to the Linux machine, you can run it under Wine:

Here is a screen capture Modern WPF example application running on Linux:

This application runs unmodified on Linux.

Note: I have only tested 64-bit applications.

Calling native code

You can customize your .NET app for Linux and call into native linux code with P/Invokes in your .NET code. The key is to create addition Wine DLLs that then call into Linux libraries.

The easiest way I have found to do this is to download and build the Wine source and then follow the patterns of the built-in DLLs. The Wine Developer Hints page has information on how to implement a new DLL. You can follow these instructions to create a DLL for your application.

Lets say you have a .so (examplelibrary.so) that has a method like this:

that you want to call into. To call into it, you need to make an equivalent DLL version (winExampleLibrary) that you can then pInvoke to:

Then pInvoke normally:

What to do if your application does not work

Most debuggers will not work to debug a .NET Core apps running under Wine. I have tried remote debugging with Visual Studio and Visual Studio Code without success. One debugger that does work is is dnSpy. It is a very nice debugger that can run under Wine and debug .NET Core applications that are also running under Wine.

To use dnSpy run it under wine just like any other application:

Once dnSpy is running you should be able to attach to any .NET Core application that is running under wine.

In addition to using dnSpy, logging is often a convenient way to debug issues that you run into.

Console.WriteLine

Use Console.WriteLine to log any information you may need to debug issues. I highly recommend adding generous amounts of logging, asserts, and verification to your app. When catching unexpected exceptions, be sure to log the exception and call stack from the exception so you can easily determine the location of the error.

I recommend installing general exception handlers you can you catch unhandled exceptions and log them as well.

Dispatcher has an UnhandledException event that can be registered and used to log any unhandled exceptions from the dispatcher.

AppDomain also has an UnhandledException event that can be used to log any unhandled exceptions.

Wine Tracing

Wine is good at letting you know when your application calls unimplemented or partially implemented functionality. These messages can greatly aid in tracking down issues.

In addition to the standard tracing of Wine, you can configure even more event logging, including logging every call into Wine, to help you track down issues. More information about debug logging is available on Wine HQ’s Developer Guide

The Wine Debugging Hints may also provide some insights.

Issues I ran into

Rendering issues with different video cards

I have experienced render issues depending on which manufacturer of video card I am using. NVIDIA does the best with only minor render issues. AMD does a decent job. Intel is basically unusable. If you experience render issues (artifacts, clipping issues, …) you will likely have better luck if you switch to software rendering. You can do this by setting LIBGL_ALWAYS_SOFTWARE to 1.

With the applications I have tested using software rendering does not impact performance of the UI much at all, but it may increase CPU usage.

HTTP Listener

The default HTTPListener for Windows uses Windows APIs as part of its implementation. Unfortunately, Wine does not implement the required APIs. Luckily, System.Net.HttpListener.dll can be built so that it does not use the Windows APIs. Setting:

in the project file produces a version of HTTPListener that works on Linux.

Other issues

I ran into several other issues, like culture enumeration and file system security APIs crashing. These were all easily worked around in my applications, so I didn’t investigate them further.

The great thing is that source is available for everything (Wine, .NET Core, WPF), so it is much easier to debug and fix issues than I expected. Fixes can also be made at any level in the stack to get an app working.

Will WPF apps run on other OSes?

WPF runs on DirectX 9, so any build of Wine with reasonable DirectX support should be able to run a WPF app. I have only tried Linux.

Whats Next?

When you run a WPF application on Linux as documented here, you end up with an application that is something like this:

  • Blue — Windows build libraries
  • Green — .NET assemblies
  • Gray — Native Linux libraries

This is a pretty good place to be. The vast majority of code is shared between Windows and Linux. The application runs as a Linux process, integrates well with desktop environments, and has access to the file system and many OS services. However, this model does have challenges. Calling native code requires special work, and not having a debugger can make finding and fixing issues difficult.

It would be great to be able to switch to .NET Core for Linux, keep using WPF, and have WPF applications continue to work. Then the applications would have a boxology like this

  • Blue — Windows build libraries
  • Green — .NET assemblies
  • Gray — Native Linux libraries

In this case, the application is a standard .NET Core application for Linux. It should be debuggable by any .NET debugger that supports Linux. Calling into native libraries would not require the creation Wine wrapper DLLs.

To do this, WPF needs to be updated to compile against WineLib. In theory, this should not be too difficult. Hopefully, I will have time in the near future to work on this.

Похожие статьи