【问题标题】:Web Api Can't find ResourceWeb API 找不到资源
【发布时间】:2018-01-03 05:09:15
【问题描述】:

我正在尝试将 Web APi 包含在带有 Mvc 的 ASp.NET 应用程序中。应用程序使用身份框架来验证自己。

我添加了一个 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 有人能告诉我我做错了吗?

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

【问题讨论】:

    标签: .net asp.net-mvc vb.net asp.net-web-api asp.net-identity


    【解决方案1】:

    Web Api 需要在 MVC Routes 之前注册。而且你还需要切换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
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2014-03-22
      • 2014-12-15
      • 2022-12-29
      • 2019-06-21
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多