我正在使用 Northwind 数据库,试图了解 Asp.Net 的 WebAPI。
我的模型/控制器/全局文件如下所示。
当我导航到 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 数据库肯定有数据:
谁能看到我要去哪里错了?
谢谢,马克
模型/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
控制器/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
网络配置:
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
全球.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