Pergunta

I am a long-serving ASP.NET VB web forms programmer, but need to start using WebAPI to create a simple service. I've followed the PluralSight tutorial on http://www.asp.net, and have these two snippets:

HelloApiController.vb

Imports System.Web.Http

Namespace HelloWebApiDemo

    Public Class HelloApiController
        Inherits ApiController

        Public Function [Get]()
            Return "Hello from API at " & DateTime.Now.ToString
        End Function

    End Class

End Namespace

Global.asax.vb

Imports System.Web.Http
Imports System.Web.Http.Routing

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        GlobalConfiguration.Configuration.Routes.Add("default", New HttpRoute("{controller}"))
    End Sub

End Class

When run, the URL for retrieving information is: http://localhost:63678/helloapi

Can anyone please explain the correlation of how "{controller}" automagically maps to the above URL? I don't see the word helloapi anywhere in the code. What if I created a second class that inherits ApiController - how would IIS differentiate between which one I wanted to access?

Also, does the method name [Get]() automatically get mapped to the respective HTTP verb? Again, what happens if I wanted to give it a different name?

Thanks.

Foi útil?

Solução

One of the great things about web API is that it works by convention. Web API is able to route the GET request to HelloApiController by using the convention of URI path getting mapped to the class name prefix (leaving out Controller). If you have another controller, say FooController, the URI of http://server/foo is what is needed to hit your second controller.

As for the method names, it goes by HTTP verb. By default, the method names of Get and the method names starting with Get such as GetFoo is mapped to HTTP GET and so on. This can be changed. The concept of routing is very powerful and it cannot be explained here through an answer. I highly recommend Mike Wasson's getting started stuff in ASP.NET web site. Check out this and the rest of the stuff.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top