×
=0) { let js = text.slice(pos1, pos2); + '<\/' + "script" + '>'; arrText.push(js); // next pos1 = pos2; continue; } } } break; } return arrText; } function OpenDialog(parentDiv, urlContent) { parentDiv = document.getElementById('modal-background'); // new !!!!!!! parentDiv.appendChild(document.getElementById('modal-template')); document.getElementById('modal-background').style.display = "block"; document.getElementById('modal-template').style.display = "flex"; // !!!!! document.getElementById('modal-body').innerHTML = ""; post_url(urlContent, "", function(text_from_server) { var element = document.getElementById('modal-body'); element.innerHTML = text_from_server; // add scripts var arrJSText = get_scripts(text_from_server); for (var i=0; i
dir.by
Search
Programming, development, testing
→
.NET Core Web API (Protocol-based Web Service HTTP)
→
Create a new .NET Core Web API application on C#
Looked at
3702
times
Create a new .NET Core Web API application on C#
last updated: 21 October 2024
Step 1. Open Visual Studio
If you do not have
Visual Studio
installed you need
install Visual Studio...
Open
Visual Studio 2022
or
Open
Visual Studio 2019
Step 2. Let's create a new application
I'm creating a new app named
WebApiCore
Visual Studio 2022
Visual Studio 2019
Note!
Options in
Visual Studio 2022
Configure for HTTPS
Hide << ...
Let's look at >> ...
If we use
[v]
Configure for HTTPS
This means that the project will use the
https
protocol
If we don't use
[ ]
Configure for HTTPS
This means that the project will use the
http
protocol
Enable Docker
Hide << ...
Let's look at >> ...
If we use
[v]
Enable Docker
This means that
This C# WEB API project can be packaged in Docker ...
Use controllers (uncheck to use minimal APIs)
Hide << ...
Let's look at >> ...
If we use
[v]
Use controllers (uncheck to use minimal APIs)
This means that the project will use the
Controller
class for the convenience of
http
queries.
Just like that:
C#
using
Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Logging;
using
System;
using
System.Collections.Generic;
namespace
WebAPI.Controllers
{
[ApiController]
[Route(
"[controller]"
)]
public
class
WeatherForecastController
: ControllerBase
{
[HttpGet]
public
string
Today()
{
return
"22 degree"
;
}
}
}
If we don't use
[ ]
Use controllers (uncheck to use minimal APIs)
This means that it will be harder to process
http
requests
C#
namespace
WebApiCore
{
public
class
Program
{
public
static
void
Main(
string
[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapGet(
"/WeatherForecast"
, (HttpContext httpContext) =>
{
return
"22 degree"
;
});
app.Run();
}
}
}
Enable OpenAPI support
Hide << ...
Let's look at >> ...
If we use
[v]
Enable OpenAPI support
This means that the project will have
Swagger
After compiling and running the project, we will see that
Swagger
will run:
If we don't use
[ ]
Enable OpenAPI support
This means that the project will NOT have
Swagger
After compiling and running the project, we will see:
Do not use top-level statements
Hide << ...
Let's look at >> ...
If we use
[v]
Do not use top-level statements
This means that the
Program.cs
file contains the
Program
class and inside the
C#
command.
Just like that:
C#
namespace
WebApiCore
{
public
class
Program
{
public
static
void
Main(
string
[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
If we don't use
[ ]
Use controllers (uncheck to use minimal APIs)
This means that there is no
Program
class in the
Program.cs
file, only
C#
commands.
Just like that:
C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 2.
A new application has been created, we are looking at the files
Step 3.
Let's change the code in the file WeatherForecastController.cs
C#
File
WeatherForecastController.cs
using
Microsoft.AspNetCore.Mvc;
namespace
WebApiCore.Controllers
{
[ApiController]
[Route(
"weather"
)]
public
class
WeatherForecastController
: ControllerBase
{
[HttpGet]
public
string
Today
()
{
return
"22 degree"
;
}
[HttpGet(
"tomorrow"
)]
public
string
Tomorrow
()
{
return
"25 degree (hot)"
;
}
}
}
Explanation!
Controller
is the class in which requests are processed.
We have 2 requests processed: method
Today
and method
Tomorrow
Attributes
[ApiController]
indicates that this class is a query processor
[Route("weather")]
Specifies in which folder the request is being processed
In this case, the folder is called
weather
[HttpGet]
indicates that this method is a response to an unnamed
get
query
If you open in
Google Chrome
:
https://localhost:7211/weather
We'll see:
that is, our
Today()
method will be executed
[HttpGet("tomorrow")]
indicates that this method is a response to a
get
query named
tomorrow
If you open in
Google Chrome
:
https://localhost:7211/weather/tomorrow
We'll see:
that is, our
Tomorrow()
method will be executed
Step 4.
Let's change the code in the file launchSettings.json
In this file, I've changed
launchUrl
.
If you run
.NET Core Web API
the project in
Visual Studio
,
Google Chrome
will open with
launchUrl
.
launchUrl
is the URL for convenience so that you can always see my
Today
handler when the project starts.
Attention!
If you change something in the file
launchSettings.json
or
appsettings.json
, then you need to do
Rebuild
and only then start the project.
json
File
launchSettings.json
{
"$schema"
:
"https://json.schemastore.org/launchsettings.json"
,
"iisSettings"
: {
"windowsAuthentication"
: false,
"anonymousAuthentication"
: true,
"iisExpress"
: {
"applicationUrl"
:
"http://localhost:61246"
,
"sslPort"
: 44374
}
},
"profiles"
: {
"WebApiCore"
: {
"commandName"
:
"Project"
,
"dotnetRunMessages"
: true,
"launchBrowser"
: true,
"launchUrl"
:
"weather"
,
"applicationUrl"
:
"https://localhost:7211;http://localhost:5082"
,
"environmentVariables"
: {
"ASPNETCORE_ENVIRONMENT"
:
"Development"
}
},
"IIS Express"
: {
"commandName"
:
"IISExpress"
,
"launchBrowser"
: true,
"launchUrl"
:
"weather"
,
"environmentVariables"
: {
"ASPNETCORE_ENVIRONMENT"
:
"Development"
}
}
}
}
Step 5.
Run the project on a computer (Windows)
Click on the menu:
Debug
→
Start Without Debugging
And we'll see the result:
На заметку!
Если запускаем первый раз то увидим:
Нажмем
yes
чтобы доверять
https
сертификату
Нажмем
yes
чтобы установить
https
сертификат
Download the example
WebApiCore.zip ...
Size: 125 kilobytes
If you run the .NET Core Web API errors:
Ошибка 1
В
Visual Studio
запускаю проект
.NET Core Web API С#
и ошибка:
Your connection isn’t private
Решение:
https://dir.by/developer/web_api/error_your_connection_is_not_private ...
Ошибка 2
В
Visual Studio
запускаю проект
.NET Core Web API С#
и ошибка:
HTTP Error 500.31 - Failed to load ASP.NET Core runtime
Решение:
https://dir.by/developer/web_api/error_failed_to_load_asp_net_core_runtime/
Ошибка 3
В
Visual Studio
запускаю проект
.NET Core Web API С#
и ошибка:
Unable to connect to web server ... The web server is no longer running.
Решение:
https://dir.by/developer/web_api/error_unable_to_connect_to_web_server_the_web_server_is_no_longer_running/
Next topic →
Docker для .NET Core API приложения
Your feedback ... Comments ...
Your Name
Your comment
(www links can only be added by a logged-in user)
+ Picture
Объявления
Объявления
•
Create a new .NET Core Web API application on C#
Docker
•
Docker для .NET Core API приложения
Azure (Web service) для .Net Core 5.0 приложения
•
Создаем Azure Web service с типом Net Core 5. То есть создаем пустой web server с типом Net Core 5
•
Приложение .Net Core 5 Web Api делаем publish в → Azure | используем Visual Studio 2019
Orleans
•
Добавляем Orleans Silo в .NET Core Web Api приложении
•
Orleans dashboard
•
Orleans in Docker
PostMan
•
Download the program PostMan (to send data to the app Web API)
•
PostMan send data in the format json for the application Web API
•
PostMan error: Could not get any response. SSL certificate
Дополнительные темы, вопросы
•
Date request format in the .NET Core 5.0 Web API
•
What's the difference (which is better to use) WCF or Web API ?
Ошибки
•
Error "Your connection isn’t private. Attackers might be trying to steal your information from (for example, passwords, messages, or credit cards). NET::ERR_CERT_INVALID" | .NET Core Web API application to C#
•
Error "HTTP Error 500.31 - Failed to load ASP.NET Core runtime" | I run .NET Core Web API the application on C#
•
Error "Unable to connect to web server ... The web server is no longer running." | I run .NET Core Web API the application on C#
WWW sites to explore Web API
•
Books to study Web API
Ваши вопросы присылайте по почте:
info@dir.by