user14394673
user14394673

Reputation:

HTTPGet Action Method gets error messages

I was trying to use the HttpGet Action Method but I got an error message.
I followed the tutorial from this Youtube Video to make a CRUD app but I got 2 error messages so I copied the code from here but it did not make a difference.

I also installed the NuGet Packages Microsoft.AspNetCore.Http and System.Net.Http thinking that maybe I have the problems because a package was missing but it did not help either.

Below is the code under PeopleController.cs:

using CuriousDriveTutorial.Data.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace CuriousDriveTutorial.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PeopleController: ControllerBase
    {
        //dependancy injection for applicationdbcontext
        private readonly ApplicationDBContext context1;
        public PeopleController(ApplicationDBContext context) { this.context1 = context; }
    }

    //get action method
    [HttpGet]
    public async Task<IActionResult> Get() => await context1.People.ToListAsync();

}

And below are the error messages for line 22 ( public async Task<IActionResult> Get() => await context1.People.ToListAsync(); ):

The red squiggly line is under the words Get and context1. Also, I don't know if this information is useful but the project is a Blazor app.

Upvotes: 0

Views: 192

Answers (2)

hoge
hoge

Reputation: 82

Get() method is defined outside of your PeopleController class. You should define your method inside your class. Like this.

public SomeClass
{
  //blur
  public void SomeMethod()
  {
       //do nothing.
  }
}

Upvotes: 1

CGundlach
CGundlach

Reputation: 671

You close the class PeopleController in line 18, thus the method Get isn't part of the class anymore. In C# functions can't be members of namespaces directly. For the same reason it has no access to the variable context1.

Solution: Move the brace from line 18 to line 23.

Upvotes: 1

Related Questions