1
我使用Northwind數據庫,嘗試瞭解Asp.Net的WebAPI。ASP.Net WebAPI URL不返回任何數據
我的模型/控制器/全局文件如下所示。
當我瀏覽到本地主機:XXXX/API /員工/ 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 /無。
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
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
的你在頂部顯示的兩個GetValue函數和EmployeesController.vb是不同的 –
你怎麼知道它返回null?您使用什麼代碼來製作HTTP請求?您是否嘗試過使用提琴手查看電線上的請求? –
嗨達雷爾 - 是的,在Internet Explorer中它打開一個文本文件,它的所有內容都是NULL - F12的IE工具中的請求是:密鑰\t值 請求\t GET/api/employees/5 HTTP/1.1 - 答覆機構是空的 – Mark