Exercise on Contact Form with Middleware in ASPNET Core

Use the concepts learnt till now, and without using razor, and without mvc framework, create a contact form that has a text box (cusName) and a date picker (meetOn), and that posts data to your asp.net core application. The application echoes this data back to the browser.

Categories | About |     |  

Parveen,

Exercise on ASP.NET Core Middleware

Use the concepts learnt till now, and without using razor, and without mvc framework, create a contact form that has a text box (cusName) and a date picker (meetOn), and that posts data to your asp.net core application. The application echoes this data back to the browser.

Solution

This is the Startup class.

public class Startup
{

  public void Configure(IApplicationBuilder app)
  {

    app.UseRouting();

    app.UseEndpoints(endpoints =>

    {

      endpoints.MapGet("/", async context =>

      {

        StringBuilder sbHtml = new StringBuilder();

        sbHtml.Append("<form method='POST'>");

        sbHtml.Append("Name: <input type='text' name='cusName' />");

        sbHtml.Append("<br />");

        sbHtml.Append("Date: <input type='date' name='meetOn' />");

        sbHtml.Append("<br />");

        sbHtml.Append("<input type='submit' />");

        sbHtml.Append("</form>");

        context.Response.ContentType = "text/html";

        await context.Response.WriteAsync(sbHtml.ToString());

      });

      // post requests 
      endpoints.MapPost("/", async context =>

      {

        HttpRequest req = context.Request;

        String cusName = req.Form["cusName"];

        DateTime meetOn = Convert.ToDateTime(req.Form["meetOn"]);

        await context.Response.WriteAsync($"Meeting with {cusName} on {meetOn}");

      });

    });

    // any other request is bad 
    app.Run(async context =>

    {

      // bad request 
      context.Response.StatusCode = 400;

      await Task.CompletedTask;

    });

  }

}

Comments and Discussion

Please write your comments and discussion on the following youtube video itself:


This Blog Post/Article "Exercise on Contact Form with Middleware in ASPNET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Comments and Discussion