ASP.NET Core 6.0 - API Implementation

This article describes implementing API support for an existing razor pages project. I will assume you have downloaded the ASP.NET Core 6.0 - Users With Comments Project.

Users With Comments Project and Article Series

The ASP.NET Core 6.0 - Users With Comments Project (UWCP) implements public member profiles and a moderated comment workflow from user submission to admin publication. I started with the ASP.NET Core 6.0 - Users With Device 2FA Project (UWD2FAP) which implements WebAuthn, also known as FIDO2, instead of authenticator apps. The latest version of the UWCP is published at Preview. KenHaggerty. Com. I encourage you to register and submit a comment. Details, screenshots, and related articles can be found at ASP.NET Core 6.0 - Users With Comments Project. The details page includes the version change log.

Visual Studio 2022 (VS 2022) is required to develop .NET 6 and ASP.NET Core 6.0 applications. .NET 6 and ASP.NET Core 6.0 are Long Term Support (LTS) releases and will be supported until November 08, 2024. .NET 5 is a Current release and will be supported until May 08, 2022. .NET 3.1 is a LTS release and will be supported until December 3, 2022. See .NET and .NET Core release lifecycle.

When I started to refactor the comments feature, I realized I had the same code on multiple razor pages. I developed Comments, MemberProfile, and ProfileImage ApiControllers to consolidate the code. Adding support for ApiControllers is not difficult for an existing razor pages project. The UWCP also implements the Swashbuckle. AspNetCore Nuget package.

Install Swashbuckle.AspNetCore Nuget.

Add the controllers and Swagger services to the WebApplicationBuilder in Program.cs.

// API Support
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();

Map endpoints for controllers and add Swagger middleware to the request pipeline in Program.cs.

// API Support
app.MapControllers();
app.UseSwagger();
app.UseSwaggerUI();

Add an API folder to project's root. Right click the folder then Add > New Item.

Add API Folder.
Add New Item.

Select API Controller with read/write actions.

Add API Controller.

The ValuesController after applying global usings and file scoped namespaces.

namespace UsersWithComments.Api;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<ValuesController>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<ValuesController>
    [HttpPost]
    public void Post([FromBody] string value)
    {
    }

    // PUT api/<ValuesController>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/<ValuesController>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

The Swagger UI generates documentation for the API interface at /swagger/index.html.

Swagger UI.

Expanding a method displays the required parameters.

Method Parameters.

Executing a method displays the response.

Method Response.

Add JavaScript to Index.cshtml to test the configuration.

@section Scripts {
<script>
    function verifyConfiguration() {
        return fetch('/api/values',
            { method: 'get', credentials: 'same-origin', headers: { 'Content-Type': 'application/json;charset=UTF-8' } })
            .then(function (response) { if (response.ok) return response.text(); else throw new Error("HTTP status code: " + response.status); })
            .then(function (text) { try { return JSON.parse(text); } catch (err) { throw Error(err); } })
            .then(function (responseJSON) {
                console.log(JSON.stringify(responseJSON));
                //alert(JSON.stringify(responseJSON));
                showMessageModal(JSON.stringify(responseJSON), 'alert-success');
            }).catch(function (error) { showMessageModal(error, 'alert-danger'); });
    }

    document.addEventListener('DOMContentLoaded', function () {
        verifyConfiguration();
    });
</script>
}
Verify Configuration Alert.

The UWCP implements showMessageModal with dynamic-modals.js.

Verify Configuration Message Modal.
Ken Haggerty
Created 06/01/22
Updated 06/19/22 15:27 GMT

Log In or Reset Quota to read more.

Article Tags:

Scaffold VS 2022
Successfully completed. Thank you for contributing.
Contribute to enjoy content without advertisments.
Something went wrong. Please try again.

Comments(0)

Loading...
Loading...

Not accepting new comments.

Submit your comment. Comments are moderated.

User Image.
DisplayedName - Member Since ?