problem with API

M J 661 Reputation points
2022-07-19T22:42:52.29+00:00

I have the following in my ApiController
public IEnumerable<Game> GetAllGames()
{
Game game = new Game();
List<Game> Games = game.ListGames();
return Games;
}

I have also tried
public IHttpActionResult GetAllGames()
{
Game game = new Game();
List<Game> Games = game.ListGames();
return Ok(Games);
}

When i run in postman i get the following
{
"GameId": null,
"GameName": null,
"RecommendedAges": null,
"Synopsis": null,
"Link": null,
"Playtime": null,
"CheckedOut": false,
"MinPlayers": 0,
"MaxPlayers": 0,
"MinPlaytime": 0,
"SearchType": 0,
"Num": 0,
"Genre": null,
"GenreName": null,
"Email": null,
"DateCheckedOut": "0001-01-01T00:00:00",
"RowId": null,
"GamePhoto": [],
"GameGenre": []
}

I know the method ListGames works because it works on the mvc page

What am I doing wrong?

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
301 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,141 Reputation points
    2022-07-23T10:38:27.617+00:00

    I'm not sure if you read my last post. I think the problem is you do not understand REST (Web API) fundamentals.

    If you are using the default Web API template in Visual Studio then "getallgames" in the URL below is a route parameter NOT an action name.

    http://dataconnective.com/api/games/getallgames  
    

    Web API does not use action names in the URL. Take a look at the App_Start\WebApiConfig.cs.

    config.Routes.MapHttpRoute(  
        name: "DefaultApi",  
        routeTemplate: "api/{controller}/{id}",  
        defaults: new { id = RouteParameter.Optional }  
    

    As you can see there's no action in the route template.

    To prove this fact let's look at your sample application. You can enter either of the two URLs below yet the same result is returned.

    http://dataconnective.com/api/games/getallgames
    http://dataconnective.com/api/games/blah

    The reason your break point is not hit is because the getallgames action is NOT being hit. The action that is invoked is the one with a route parameter.

    Look at the following example.

    public class GameController : ApiController  
    {  
        public IHttpActionResult GetAllGames()  
        {  
            Game game = new Game();  
            List<Game> Games = game.ListGames();  
            return Ok(Games);  
        }  
      
        public IHttpActionResult Getbyid(string id)  
        {  
            return Ok(id);  
        }  
    }  
    

    If I enter https://localhost:44310/api/game/getallgames in the browser, the result is "getallgames" which is the "id" route parameter found in the Getbyid(string id) action.

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">getallgames</string>  
    

    The Getbyid(string id) is invoked not GetAllGames(). This is a fundamental building block in REST and this type of information is openly covered in every Web API getting started tutorial.

    FYI, when I enter http://dataconnective.com/api/games in the browser's address bar, your API returns an 500 Internal Server Error.

    <Error>  
    <Message>An error has occurred.</Message>  
    </Error>  
    

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,141 Reputation points
    2022-07-20T17:33:05.863+00:00

    Joe, I included the class and method as an attachment in my previous response

    The JSON results in your first post do not match the Game model or a collection. Therefore, I can only assume the JSON results you've posted are not coming from GetAllGames() or you did not share the correct JSON results. Also, the Game model properties do not exactly match the result set from the stored procedure!?

    I crafted a test using your Game class and Web API action. The JSON has the following format. Notice the properties that do not have a procedure result are null or a default value.

    [  
        {  
            "GameId": "1",  
            "GameName": "Game 1",  
            "RecommendedAges": "18",  
            "Synopsis": "Synopsis 1",  
            "Link": "Link 1",  
            "Playtime": "Playtime",  
            "CheckedOut": false,  
            "MinPlayers": 1,  
            "MaxPlayers": 4,  
            "MinPlaytime": 3,  
            "SearchType": 0,  
            "Num": 0,  
            "Genre": null,  
            "GenreName": null,  
            "Email": null,  
            "DateCheckedOut": "0001-01-01T00:00:00",  
            "RowId": null  
        },  
        {  
            "GameId": "2",  
            "GameName": "Game 2",  
            "RecommendedAges": "14",  
            "Synopsis": "Synopsis 1",  
            "Link": "Link 2",  
            "Playtime": "Playtime",  
            "CheckedOut": false,  
            "MinPlayers": 2,  
            "MaxPlayers": 3,  
            "MinPlaytime": 4,  
            "SearchType": 0,  
            "Num": 0,  
            "Genre": null,  
            "GenreName": null,  
            "Email": null,  
            "DateCheckedOut": "0001-01-01T00:00:00",  
            "RowId": null  
        }  
    ]  
    

    Please troubleshoot your code!


  2. Lan Huang-MSFT 25,876 Reputation points Microsoft Vendor
    2022-07-22T08:45:13.67+00:00

    Hi @M J ,
    I wrote an example based on the code you provided. You can refer to it.

    I don't understand why it won't hit the breakpoints.

    Where did you hit the breakpoint?I suggest you still check the database.

     public class GameController : ApiController  
        {  
            // GET: Game  
            public IHttpActionResult GetAllGames()  
            {  
                 
                Game game = new Game();  
                List<Game> list = game.ListGames();  
                  
                return Ok(list);  
            }  
        }  
    

    public class Game  
    	{  
    		public string GameId { get; set; }  
    		[Required, Display(Name = "Game Name"), StringLength(200)]  
    		public string GameName { get; set; }  
    		[Required, Display(Name = "Recommended Age"), StringLength(25)]  
    		public string RecommendedAges { get; set; }  
      
    		[StringLength(100)]  
    		public string Link { get; set; }  
      
      
      
    		public List<Game> ListGames()  
    		{  
    			using (SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))  
    			{  
    				using (SqlCommand oCmd = new SqlCommand())  
    				{  
    					try  
    					{  
    						oCmd.CommandText = "ListGames";  
    						oCmd.CommandType = CommandType.StoredProcedure;  
    						oCmd.Connection = oConn;  
    						oConn.Open();  
    						using (SqlDataReader reader = oCmd.ExecuteReader())  
    						{  
    							List<Game> myList = new List<Game>();  
    							while (reader.Read())  
    							{  
    								Game game = new Game  
    								{  
    									GameId = reader[0].ToString(),  
    									GameName = reader[1].ToString(),  
    									RecommendedAges = reader[2].ToString(),  
    									Link = reader[3].ToString(),  
    								};  
    								myList.Add(game);  
    							}  
    							return myList;  
    						}  
    					}  
    					catch (Exception ex)  
    					{  
      
    						return null;  
    					}  
    					finally  
    					{  
    						oCmd.Dispose();  
    						oConn.Close();  
    					}  
    				}  
    			}  
    		}  
    	}  
    

    223600-image.png
    223694-image.png
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.