我正在使用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数据库肯定有数据:
有人能看到我出错的地方吗?
谢谢,Mark
型号/ 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
的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
答案 0 :(得分:1)
路由参数与功能参数之间存在冲突
你问题的第一部分
Public Function GetValue(ByVal ID As Integer)As Employee
在控制器中
Public Function GetValue(ByVal EmployeeID As Integer)As Employee
您在路由中使用ID
routes.MapHttpRoute( _
name:="DefaultApi", _
routeTemplate:="api/{controller}/{id}", _
defaults:=New With {.id = RouteParameter.Optional} _
)