我正在尝试将Web APi包含在带有Mvc的ASp.NET应用程序中。该应用程序使用Identity Framework进行身份验证。
我添加了一个WebApiConfig
Imports System.Web.Http
Namespace ActualizadorApp.Api
Public NotInheritable Class WebApiConfig
Private Sub New()
End Sub
Public Shared Sub Register(config As HttpConfiguration)
' TODO: Add any additional configuration code.
' Web API routes
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(name:="Api", routeTemplate:="api/{controller}/{id}", defaults:=New With {
Key .id = RouteParameter.[Optional]
})
' WebAPI when dealing with JSON & JavaScript!
' Setup json serialization to serialize classes to camel (std. Json format)
Dim formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter
formatter.SerializerSettings.ContractResolver = New Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
End Sub
End Class
End Namespace
在Global.Asax中我引用了这个配置
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterRoutes(RouteTable.Routes)
WebApiConfig.Register(GlobalConfiguration.Configuration)
ModelBinders.Binders.Add(GetType(Decimal), New DecimalModelBinder())
ModelBinders.Binders.Add(GetType(Decimal?), New DecimalModelBinder())
End Sub
通过/ token进行身份验证是正确的并正确返回令牌,但在以下GET调用驱动程序时,客户端返回404 有人能告诉我,我做错了吗?
Imports System.Web.Http
<Authorize()>
Public Class TestController
Inherits ApiController
'public TestController() { }
' GET api/test
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
' GET api/test/5
Public Function GetValue(id As Integer) As String
Return "value"
End Function
End Class
答案 0 :(得分:1)
Web Api需要在MVC路由之前注册。此外,您还需要切换GlobalConfiguration
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
'Regsiter Web API routes before MVC routes
GlobalConfiguration.Configure(WebApiConfig.Register)
'MVC routes
RegisterRoutes(RouteTable.Routes)
ModelBinders.Binders.Add(GetType(Decimal), New DecimalModelBinder())
ModelBinders.Binders.Add(GetType(Decimal?), New DecimalModelBinder())
End Sub