0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WEBアプリにAPIを作成する

Posted at

VB.Netで作成したWEBアプリに対してAPIを作成する。
※WEBアプリはすでに作成済みとし、そこに新たにAPIを実装する

API フォルダ構成

API
├── Controller
│     └── SampleController.vb
├── Param
│    └── SampleParam.vb
├── DataSet
│    └── dsSample.xsd
└── Res
     └── SampleRes.vb

  • Controller: APIのエンドポイントを定義するコントローラーを格納
  • Param: APIのパラメータ定義を格納
  • DataSet: データベースとのやり取りに使用するDataSetファイルを格納
  • Res: APIのレスポンスに関連する定義を格納

App_Startフォルダに「WebAipConfig.vb」がない場合は新規で作成する。

  • WebAipConfig.vb: ルート設定を行う

アプリ起動時に最初に読み込まれる「Grobal.asax」も編集する。

パッケージをインストール

NuGet パッケージの管理から以下のパッケージをインストールする。

  • Microsoft.AspNet.WebApi
  • System.Text.Json: POSTでJSONを受け取る場合
  • System.Runtime.CompilerServices.Unsafe

Controller

SampleController.vb
Imports System.Web.Http
Imports project.API.Param
Imports project.API.Res

Namespace project.API.Controller
    Public Class SampleController
        Inherits ApiController

        ' POST: api/Sample
        <HttpPost>
        Public Function Post(<FromBody> param As SampleParam) As SampleRes
            Dim response As New SampleRes()

            ' パラメータのチェック
            If param IsNot Nothing AndAlso Not String.IsNullOrEmpty(param.ReqestParam) Then
                ' 正常なレスポンスを設定
                response.Result = True
                response.ErrorCd = ""
                response.ErrorMessage = ""
                response.Message = "OKですよ"
            Else
                ' エラーレスポンスを設定
                response.Result = False
                response.ErrorCd = "01"
                response.ErrorMessage = "パラメータが不正です。"
                response.Message = Nothing
            End If

            Return response
        End Function
    End Class
End Namespace

Param

SampleParam.vb
Namespace API.Param
    Public Class SampleParam
        Public Property ReqestParam As String
    End Class
End Namespace

Res

SampleRes.vb
Namespace API.Res
    Public Class SampleRes
        Public Property Result As Boolean
        Public Property ErrorCd As String
        Public Property ErrorMessage As String
        Public Property Message As String
    End Class
End Namespace

WebApiConfig

WebApiConfig.vb
Imports System.Web.Http

Public Class WebApiConfig
    Public Shared Sub Register(ByVal config As HttpConfiguration)
        ' Web APIの属性ルートを有効にする
        config.MapHttpAttributeRoutes()

        ' デフォルトルートの設定
        config.Routes.MapHttpRoute(
    name:="DefaultApi",
    routeTemplate:="api/{controller}",
    defaults:=New With {.id = RouteParameter.Optional}
)
    End Sub
End Class

Grobal

Grobal.asax
Imports System.Web.Optimization
Imports System.Web.Http

Public Class Global_asax
    Inherits HttpApplication

    Sub Application_Start(sender As Object, e As EventArgs)
        ' アプリケーションの起動時に呼び出されます
        RouteConfig.RegisterRoutes(RouteTable.Routes)
        BundleConfig.RegisterBundles(BundleTable.Bundles)

        ' Web APIの設定を登録 ※今回はここを追加した
        GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' ハンドルされていないエラーが発生したときに実行するコードです
        System.Web.HttpContext.Current.Server.Transfer("~/customError.aspx")
    End Sub
End Class

APIを実行する

※Postmanでlocalhostに対してテストする際はデスクトップアプリ版を使用する
 コードがあっているはずなのにリクエストできず詰まったことがありますw

エンドポイント

http://localhost:<ポート番号>/api/Sample

リクエストボディ
リクエストボディ
{
    "ReqestParam": "test"
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?