Asp.NetのWebAPIを理解するために、Northwindデータベースを使用しています。
私のモデル/コントローラー/グローバルファイルを以下に示します。
localhost:xxxx / api / employees / 5に移動すると、正しいコントローラーに正しく移動します。
' GET /api/employees/5
Public Function GetValue(ByVal ID As Integer) As Employee
Dim emp As Employee = db.Employees.Find(ID)
Return emp
End Function
...ただし、empはNull/Nothingを返します。
Northwindデータベースには間違いなくデータがあります。
誰かが私がどこで間違っているのかわかりますか?
ありがとう、マーク
Models / Employee.vb:
Imports System.Data.Entity
Namespace MvcApplication21
Public Class Employee
Public Property EmployeeID() As Integer
Public Property FirstName() As String
Public Property LastName() As String
End Class
Public Class EmployeeDBContext
Inherits DbContext
Public Property Employees() As DbSet(Of Employee)
End Class
End Namespace
Controllers / EmployeesController.vb
Imports System.Web.Http
Imports MvcApplication21
Imports MvcApplication21.MvcApplication21
Public Class EmployeesController
Inherits ApiController
Private db As New EmployeeDBContext
' GET /api/employees
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
' GET /api/employees/5
Public Function GetValue(ByVal EmployeeID As Integer) As Employee
Dim employee As Employee = db.Employees.Find(EmployeeID)
Return employee
End Function
Web.config:
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Global.asax.vb
Imports System.Web.Http
Imports System.Web.Optimization
Public Class WebApiApplication
Inherits System.Web.HttpApplication
Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)
filters.Add(New HandleErrorAttribute())
End Sub
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapHttpRoute( _
name:="DefaultApi", _
routeTemplate:="api/{controller}/{id}", _
defaults:=New With {.id = RouteParameter.Optional} _
)
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
End Sub