2012-05-22 49 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} _  
)