Question

I have a simple Web API (sitting inside webforms site) that generates a simple "Tip of the Day". The code is as follows:

AppCode\TipOfTheDayController.vb

Imports System.Net
Imports System.Web.Http

Public Class TipOfTheDayController
    Inherits ApiController

    Private Function GenerateTip() As TipOfTheDay
        Dim tipCol As New List(Of Tip)
        tipCol.Add(New Tip("Tip Text 01"))
        tipCol.Add(New Tip("Tip Text 02"))
        tipCol.Add(New Tip("Tip Text 03"))
        Dim rnd As New Random
        Dim i As Int16 = rnd.Next(0, tipCol.Count - 1)
        Dim td As New TipOfTheDay
        td.TipString = tipCol(i).TipString
        td.TipNumber = i
        Return td
    End Function

    Public Function GetTip() As TipOfTheDay
        Return GenerateTip()
    End Function

End Class

Public Class Tip

    Public Property TipString As String

    Public Sub New(ts As String)
        Me.TipString = ts
    End Sub

End Class

Public Class TipOfTheDay

    Public Property TipString As String
    Public Property TipNumber As String

End Class

I am trying to wire this up so that it can be called using

http://www.mysite.com/api/tips

Assuming the above URL is okay, I cannot figure this bit out in Global.asax. I've seen loads of examples online but all have an optional "ID" value which I don't need. Can anyone please show me what I need to do to retrieve my random "tip" from the API?

<%@ Application Language="VB" %>
<%@ Import Namespace="System.Web.Routing" %>
<%@ Import Namespace="System.Web.Optimization" %>
<%@ Import Namespace="System.Web.Http" %>

<script runat="server">
    Sub RegisterRoutes(routes As RouteCollection)
        routes.MapHttpRoute("TipOfTheDay", "api/tips")
    End Sub    
</script>
Was it helpful?

Solution

The routing is looking for an Index Action on your controller if the action was not specified in the route or by entering into the url. Rename your GetTip function to Index.

If that is not acceptable, you can add a route similar to the following in lieu of your current route.

routes.MapHttpRoute("TipOfTheDay", "api/tips", new { Controller = "TipOfTheDay" Action = "GetTip" });

I wouldn't recommend this route, however, since it will try to use GetTip as the default action every time one is not specified.

Here is a good resource for routing in a web forms application: http://msdn.microsoft.com/en-us/library/dd329551.ASPX

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top