坂本  健一

坂本 健一

1655982600

.NET Core MVCWebAPIのSwagger

Swagger(OpenAPI)は、RESTAPIを記述するための言語に依存しない仕様です。これにより、コンピューターと人間の両方が、ソースコードに直接アクセスしなくてもRESTAPIの機能を理解できます。Swagger UIは、生成されたOpenAPI仕様を使用して、サービスに関する情報を提供するWebベースのUIを提供します。SwaggerUIはPostmanの代替手段です。

私は自分の記事でSwaggerを数回以上使用しましたが、さまざまなトピックで使用されるマイナーなツールとして使用しました。Swaggerの情報を取得しようとしたとき、これらの記事から検索する必要がありましたが、これは便利ではありませんでした。そこで、これら2つの記事、特にSwagger for .NET MVCWebAPIまたは.NETCoreMVCWebAPIについて書き直しました。

序章

新しい.NETCore5.0 Web APIプロジェクトを作成した場合、WebAPI用のSwaggercientがデフォルトでインストールされます。現在のケースでは、.NET Core 5.0を使用していますが、Web APIはMVCモジュールで作成されているため、Swaggerを手動でインストールする必要があります。この方法は、5.0より前の.NETCoreバージョンで機能します。

この記事は、私の別の記事の一部です 。MVCによるWeb APIの使用.NETCore(1)、サーバー、およびフレームワークでは、Swagger関連の部分がここにあります。そこから詳細を見ることができます。

ステップ1-ASP.NETCoreMVCアプリケーションを作成する

アプリのビルドには、Visual Studio201916.8と.NET5.0SDKのバージョンを使用します。

  1. Visual Studioを起動し、[新しいプロジェクトの作成]を選択します。
  2. [新しいプロジェクトの作成]ダイアログで、[ASP.NETCoreWebアプリケーション]>[次へ]を選択します。
  3. [新しいプロジェクトの構成]ダイアログで、 MVCCallWebAPI プロジェクト名を入力します。
  4. [作成]を選択します。
  5. [新しいASP.NETCoreWebアプリケーションの作成]ダイアログで、[次のコマンドを選択します。
    1. ドロップダウンの.NETCoreおよびASP.NETCore5.0。
    2. ASP.NET Core Webアプリ(Model-View-Controller)。
    3. 作成

アプリをビルドして実行すると、次の画像にアプリが表示されます。

ステップ2〜3-EntityFrameworkを使用したアクションを備えたScaffoldAPIコントローラー

記事「 .NETCore(1)、サーバーおよびフレームワークでMVCによるWebAPIの消費」を参照してください 。

B:最初にEntityFrameworkコードを使用してWebAPIを追加する

  • ステップ1:新しいデータベースコンテキストを設定する
  • ステップ2:EntityFrameworkコードの最初のアプローチを使用してデータベースを操作します。
  • ステップ3、:EntityFrameworkを使用したアクションを備えたScaffoldAPIコントローラー

ステップ4-WebAPI用のSwaggerクライアントを追加する

1.Swaggerクライアントをインストールします

ソリューションエクスプローラー>[NuGetパッケージの管理]でプロジェクトを右クリックし、  Swaggerを検索します

Swashbuckle(Swagger)には3つの主要なコンポーネントがあり、そのうちの2つをインストールするだけで済みます。SwaggerGenとSwaggerUIで、Swaggerが含まれます。

2.startup.cs ファイルにSwaggerクライアントを登録し ます

Startup.ConfigureServices メソッドのサービスコレクションにSwaggerジェネレーターを追加します 。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });
    });
    ......
}

Startup.Configure メソッドで、生成されたJSONドキュメントとSwaggerUIを提供するためのミドルウェアを有効にします 。

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v2/swagger.json", "MVCCallWebAPI");
    });
    ......
}

これで、アプリを実行する準備がほぼ整いました。

ステップ5-アプリを実行してテストする

アプリを実行する前に、ファイルのヘッダーを変更します 。Views/ Shared / _layout.cshtml  Viewsを再度変更して、以下に示すSwagger(11〜13行目)を追加します。

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>

次に、アプリを実行します。

Web APIをクリックすると、Swaggerクライアント画面が表示されます。

 

ソース:https ://www.c-sharpcorner.com/article/swagger-for-net-core-mvc-web-api/

#dotnet #netcore #mvc #webapi #swagger 

What is GEEK

Buddha Community

 .NET Core MVCWebAPIのSwagger
Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

AllowAnonymous in asp.net core

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework

Authorization in asp.net core

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework

Extend IdentityUser in ASP NET Core

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework