2017-07-27 128 views
2

我正在尝试使用Mvc将Web API包含在ASp.NET应用程序中。该应用程序使用Identity Framework对自身进行身份验证。Web Api无法找到资源

我加了一个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 

通过/令牌身份验证是正确的,正确返回令牌,但在下面的GET调用给司机客户回报我404 有人可以告诉我,我做错了吗?

enter image description here

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 

回答

1

网络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