Web API在控制器的Web窗体项目中的位置在哪里?

时间:2012-12-27 20:48:46

标签: asp.net asp.net-mvc-4 asp.net-web-api

我在Web窗体项目中使用Web API。我在Global.asax中的项目Application_Start方法中有以下代码:

GlobalConfiguration.Configuration.Routes.MapHttpRoute("ApiDefault", "api/{controller}/{id}", New With {.id = RouteParameter.Optional})

这基本上是从关于该主题的Microsoft教程中复制和粘贴的。

我还有一个名为ValuesController的测试控制器。此类只是从“添加新项”向导创建控制器时获得的默认Web API控制器,并且位于名为Controllers的Web窗体站点中的文件夹中:

Imports System.Net
Imports System.Web.Http

Public Class ValuesController
    Inherits ApiController

    ' GET api/<controller>
    Public Function GetValues() As IEnumerable(Of String)
        Return New String() {"value1", "value2"}
    End Function

    ' GET api/<controller>/5
    Public Function GetValue(ByVal id As Integer) As String
        Return "value"
    End Function

    ' POST api/<controller>
    Public Sub PostValue(<FromBody()> ByVal value As String)

    End Sub

    ' PUT api/<controller>/5
    Public Sub PutValue(ByVal id As Integer, <FromBody()> ByVal value As String)

    End Sub

    ' DELETE api/<controller>/5
    Public Sub DeleteValue(ByVal id As Integer)

    End Sub

End Class

但是 - 当我转到http://localhost/api/Values时 - 我没有看到某些XML序列化字符串value1value2,而是看到如下错误消息:

<Error>
    <Message>No HTTP resource was found that matches the request URI 'http://localhost/api/Values'.</Message>
    <MessageDetail>No type was found that matches the controller named 'Values'.</MessageDetail>
</Error>

所以 - 显然,路由工作正常,因为我没有收到404消息,而是说路由本身并没有解决任何问题。但是路由应该解决某些问题 - 特别是我的ValuesController类,它甚至位于名为Controllers的文件夹中。

任何人都知道我做错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我明白了。这是因为显然MVC要求Controllers文件夹与声明路由的文件处于同一级别 - 而不是(我之前认为)只是在根级别。

呃。