坂本  健一

坂本 健一

1655887507

.NET MVC WebAPIのSwagger

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

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

  • .NET MVCWebAPIのSwagger---この記事
  • .NET Core MVCWebAPIのSwagger
  • RESTWebAPI用にカスタマイズされたSwagger

序章

この記事は別の記事の一部です: 例外処理(2)、ASP.NET MVC Web APIでは、ここにSwagger関連の部分があります。そこから詳細を見ることができます。

手順1-ASP.NETMVCWebAPIアプリを作成する

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

  • Visual Studioを起動し、[新しいプロジェクトの作成]を選択します。
  • [新しいプロジェクトの作成]ダイアログで、[ASP.NET Webアプリケーション(.NET Framework)]>[次へ]を選択します。
  • [新しいプロジェクトの構成]ダイアログで、[ ErrorHandlingWebAPI プロジェクト名]>[作成]に入力します。
  • [新しいASP.NETWebアプリケーションの作成]ダイアログで、[WebAPI]>[作成]を選択します

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

ステップ2-空のApiControllerを1つ追加します

ErrorHandlingWebAPIControllerという名前の空のapiControllerをアプリに1つ追加します 。

  • [コントローラー]>[追加]>[コントローラー]を右クリックします。
  • [新しい足場アイテムの追加]ダイアログで、左側のペインで[Web API]を選択し、
  • WebAPI2コントローラー-空>追加。
  • [コントローラーの追加]ダイアログで、[ ErrorHandlingWebAPIコントローラー名のコントローラーの変更]>[追加]を選択します。

ステップ3-コントローラーにコードを追加する

次のコードをコントローラーに追加します。

[Route("CheckId/{id}")][HttpGet]public IHttpActionResult CheckId(int id){    if (id < 10) // No error hanbdling at all:    {        int a = 1;        int b = 0;        int c = 0;        c = a / b; //it would cause exception.    }    else if (id <20) // Error handling by HttpResponseException with HttpStatusCode    {        throw new HttpResponseException(HttpStatusCode.BadRequest);    }    else if (id < 30) // Error handling by HttpResponseException with HttpResponseMessage    {        var response = new HttpResponseMessage(HttpStatusCode.BadRequest)        {            Content = new StringContent(string.Format("No Employee found with ID = {0}", 10)),            ReasonPhrase = "Employee Not Found"        };        throw new HttpResponseException(response);    }    return Ok(id);}

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

NuGet Package Manager、Visual Studioプロジェクト、

  • [ツール]>[NuGetパッケージマネージャー]>[ソリューションのNuGetの管理]を右クリックします
  • 開いたNuGet-Solutionダイアログで:[参照]、[Swaggerの検索]の順にクリックします。
  • Swashbucklev5.6.0をインストールします

 

Swaggerをインストールする前は、MVCは通常App_Startフォルダーに4つの構成ファイルを持っています。

インストール後、もう1つのファイルSwaggerConfig.csが追加され、

コード付き、

public class SwaggerConfig{    public static void Register()    {        var thisAssembly = typeof(SwaggerConfig).Assembly;        GlobalConfiguration.Configuration          .EnableSwagger(c => c.SingleApiVersion("v1", "ErrorHandlingWebAPI"))          .EnableSwaggerUi();    }}

ステップ5-デフォルトのスタートページをSwaggerに変更します

[プロジェクト]>[プロパティ]を右クリックしてプロパティページを開き、[Web]を選択し、[スタートURL]で/ swaggerを追加し、

ステップ6-アプリを実行する 

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

#mvc #webapi #csharp 

What is GEEK

Buddha Community

.NET MVC WebAPIの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

Index is not an attribute class – Error while migrating from ASP.Net MVC 5 to .Net Core

Recently one of my friends was migrating a project from ASP.Net MVC 5 to ASP.Net core 3.1. One of the challenges he faced is with the Index Attribute in data annotations. The .Net Core is not recognizing the Index attribute. When he copied his class from his MVC 5 project, he got the following error message.

clip_image001

Though the other data annotations accepted by .Net Core, this data attribute “Index” was throwing an exception.

“Index is not an attribute class”

Cool!. Let us dig into the details. You can find the related post on the Entity Framework Github page.

https://github.com/dotnet/efcore/issues/1698

https://github.com/dotnet/efcore/issues/4050

From the page, it is clear now, this is not a bug, the EF Core team didn’t migrate the Index Attribute from the EF 6. So we need to live with this.

Now the question arises, how we are going to add the Indexes to our Tables. The answer is to use the Fluent API in ASP.Net core.

You can refer to the following link on the Microsoft Site to get the details of how to apply the Index to a property.

https://docs.microsoft.com/en-us/ef/core/modeling/indexes

So the solution is to replace the Index Attribute to the Fluent API, as below.

clip_image002

In real life, you will have many classes, and adding all classes using Fluent API inside OnModelCreating() method will make your code difficult to maintain. The solution is to create a separate class derived from IEntityTypeConfiguration. This will help us define all the related configurations in a single class and then apply the configurations from the OnModelCreating() method.

Let us apply the configuration class for the above. The following is the configuration class.

clip_image003

Once you have the configuration class, you can apply the configuration in the ModelCreating() method as follows.

clip_image004

Happy Coding!

#asp.net #asp.net core 3.1 #.net core #entity framework core #mvc #migration #.net #microsoft

Eric  Bukenya

Eric Bukenya

1618666860

.NET Conf 2020 Demos & Sessions for .NET 5 + Virtual Events!

This year’s .NET Conf was the largest one yet, with over 80 live sessions across three days that were co-organized and presented by the .NET community and Microsoft. On top of all of that, it also marked the release of .NET 5.0  that brings a full set of new capabilities, performance gains, and new languages features for developers to create amazing apps. If you missed this year’s .NET Conf live stream, don’t worry because we have you covered!

#.net #.net core #asp.net #c# #.net conf #.net foundation #community #demos

Raphael  Lima

Raphael Lima

1597515900

ASP.NET Core MVC Login and Registration using Identity

Asp.Net Core MVC with Identity UI - User Authentication, Registration, Authorization, and User Profile Management.

In this ASP.NET Core MVC tutorial, we implemented a complete authentication system with the help of Identity.UI. We customized/ overridden the razor pages from the Identity API. First of all, ASP.NET Core Identity is added to an existing project. We could directly update/ override razor pages from Identity as per requirement.

MSDN documentation on email configuration: https://bit.ly/39jZBQv

Subscribe : https://www.youtube.com/channel/UCvzlnZbePin9kH-1JCKBt8Q

#asp.net core #asp.net #asp.net core mvc #.net