2012-05-22 50 views
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數據庫中肯定有數據:

Northwind snapshot

任何人都可以看到我要去哪裏錯了嗎?

謝謝,馬克


型號/ 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

的你在頂部顯示的兩個GetValue函數和EmployeesController.vb是不同的 –

+1

你怎麼知道它返回null?您使用什麼代碼來製作HTTP請求?您是否嘗試過使用提琴手查看電線上的請求? –

+0

嗨達雷爾 - 是的,在Internet Explorer中它打開一個文本文件,它的所有內容都是NULL - F12的IE工具中的請求是:密鑰\t值 請求\t GET/api/employees/5 HTTP/1.1 - 答覆機構是空的 – Mark

回答

1

有一個在你的問題的第一部分

你的路由參數和你的函數參數之間的衝突,你必須

公共職能的GetValue(BYVAL ID As Integer)作爲員工

在控制器中它是

Public Function Ge tValue(BYVAL僱員爲整數)如員工

  • 一個具有ID作爲參數,另一個有僱員作爲參數

而你正在使用的ID在你的路由

routes.MapHttpRoute(_   
    name:="DefaultApi", _   
    routeTemplate:="api/{controller}/{id}", _   
    defaults:=New With {.id = RouteParameter.Optional} _  
)