Creating an action method for getting questions

Let's implement our first action method, which is going to return an array of all the questions:

  1. Let's create a method called GetQuestions in our API controller class:
[HttpGet]
public IEnumerable<QuestionGetManyResponse> GetQuestions()
{
// TODO - get questions from data repository
// TODO - return questions in the response
}

We decorate the method with the HttpGet attribute to tell ASP.NET Core that this will handle HTTP GET requests to this resource.

We use the specific IEnumerable<QuestionGetManyResponse> type as the return type. 

  1. Let's get the questions from the repository using the _dataRepository class variable:
[HttpGet]
public IEnumerable<QuestionGetManyResponse> GetQuestions()
{
var questions = _dataRepository.GetQuestions();
// TODO - return questions in the response
}
  1. Let's return the questions in the response:
[HttpGet]
public IEnumerable<QuestionGetManyResponse> GetQuestions()
{
var questions = _dataRepository.GetQuestions();
return questions;
}

ASP.NET Core will automatically convert the questions object to JSON format and put this in the response body. It will also automatically return 200 as the HTTP status code. Nice!

  1. Let's try this by first pressing F5 in Visual Studio to start our app.
  2. In the browser that opens, change the path to end with api/questions rather than weatherforecast:

We'll see the questions from our database output in JSON format. Great, that's our first action method implemented!

  1. We are going to change the default path that invokes when the app is run to the api/questions path. Open up the launchSettings.json file in the Properties folder in Solution Explorer and change the paths referenced to api/questions:
...
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/questions",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"QandA": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/questions",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
...
  1. If the Properties folder isn't visible in Solution Explorer, then switch Show All Files on in the toolbar:

  1. Press Shift + F5 to stop the app, and then F5 to start it again. Our api/questions path will now be invoked by default in the browser.
  2. Press Shift + F5 again to stop the app. Now, we are ready for implementing more code in our next task.

That completes the action method that will handle GET requests to api/questions. We will continue implementing more action methods in the following sub-sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.44.9