Web API Intro

Tools

Just get Postman, it’s the industry standard for testing HTTP requests.

The template code for a controller is as follows (in VS, this is the ‘MVC’ template - i.e. it extends Controller, not ControllerBase):

[Route("api/[controller]")]     //don't need to change this, but if you have other controllers, you need this attribute.  The [controller] part corresponds to 'Value' in this case (the substring in your class name before 'Controller')
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()    //note that the method name doesn't matter, you can call it whatever you want
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id309g333}")]
    public string Get(int id309g333)   //Here, I'm emphasizing that the variable names in the attribute must match.
    {
        return "value";
    }

Parsing JSON from a POST parameter

You don’t need to parse any JSON, but you do need to create a class and use the [FromBody] attribute.

[HttpPost("login")]
public IActionResult Login([FromBody] UserPassModel up)
{
    ...
}

public class UserPassModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Your HTTP POST request will look like this (note the ‘JSON (application/json)’)

{
	"username":"ambrose",
	"password":"0iashdg0h3"
}

The JSON names can be lower case; .NET will automatically parse the JSON and create a UserPassModel object.

get yourself on the email list

//Powered by MailChimp - low volume, no spam

comments powered by Disqus