How do I create a HTTP post using React/Typescript Frontend and C#/.Net Backend?

Viewed 97

On the frontend code, I have a user login form that takes in the values (strings) email and password. In my userstore using MobX State Management, I have an action when a user presses the login button to submit the strings as an HTTP post

@action login = async (values: IUserFormValues) => {
    try {
      console.log(values);
      const user = await agent.User.login(values);
      runInAction(() => {
        this.user = user;
      });
      console.log(user);

    } catch (error) {
      console.log(error);
    }
  };
}

The Request looks something like this:

const responseBody = (response: AxiosResponse) => response.data;

const requests = {
  post: (url: string, body: {}) =>
    axios.post(url, body).then(sleep(1000)).then(responseBody),

};

login: (user: IUserFormValues): Promise<IUser> =>
    requests.post(`/user/login`, user)

Now to the backend, this is where I am completely lost. Not sure what to build from here:

[HttpPost("login")]
- Here -

I am gonna have to take these values and verify with a database from SQL server. There's just so many different examples using different middleware that I am just not sure what's correct or best practices.

1 Answers

Here is a very nice tutorial from the Microsoft Docs, using Entity Framework (very nice), and some dependency injection (very very nice).

Basically you create an API controller class with your CRUD methods in them like so:

namespace MyApiControllerClass
{
    [Authorize]
    [RoutePrefix("users")]
    public class UsersApiController : ControllerBase
    {
        private readonly UserContext _context;

        public UsersApiController(UserContext context)
        {
            _context = context;
        }

        [Route("/login")]
        public IHttpActionResult LoginUser(User user)
        {
            try
            {
                // login logic here

                return Ok(); // you can return whatever you need 
            }
            catch (Exception exception)
            {
                // log any issues using your preferred method of logging

                return InternalServerError(); // you can return different status codes as well. Depends on what you want
            }

        }
    }
}

You can read more about the Authorize annotation here and customize it to your liking.

Then you fire up your web project which will be available at a local URL that you can set in the project's configuration say http://localhost:4000/ which then makes your controller URL available at http://localhost:34501/users/login. Then you use this URL in your Javascript call and add the User object in the request body.

Related