Home > front end >  Cannot get basic request/response in .NET 5 web site to work
Cannot get basic request/response in .NET 5 web site to work

Time:02-18

Expanding the basic Hello World code I am trying to read a form and respond with a web page without using any of the Microsoft frameworks (e.g., no MVC). I cannot process the incoming request. What am I missing? Code:

// modified code in Hello World startup.cs:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                HttpRequest request = context.Request;
                request.EnableBuffering();   //<-- add to try to make it work
                string message = "Unknown";
                try
                {
                    var reader = request.BodyReader;
                    await reader.ReadAsync();   //<-- add to try to make it work
                    message = "Content type: "   (request.ContentType == null ? "Null" : request.ContentType)   "<br>"  
                        "Request size: "   (request.ContentLength == null ? "Null" : request.ContentLength.ToString());
                }
                catch (Exception e)
                {
                    message = "Error: "   e.Message;
                }
                await context.Response.WriteAsync(page(message));
            });
        });
    }

    public string page(string message)
    {
        return
            @"<html xmlns=""http://www.w3.org/1999/xhtml"">
            <meta httm-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
            <meta http-equiv=""expires"" content=""0"" />
            <title>
            TANCS TEST(PRODUCITON DATA)
            </title >
            <body>
            <form>
            Enter a value: <input type=""text"" id=""value"" width=20 value=""xyz"">
            <input id=""Save"" type=""submit"">
            </form>
            "   message   @"
            </body>
            </html>";
    }

CodePudding user response:

As you haven't shared the full Configure method in Startup.cs file so its not clear how you are trying the code. Additionally, you didn't shared what exactly not working and blocking you are having with.

However, if you would like to make your shared code working you should implement that in following manner:

Startup.cs file:

public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
    
                services.AddControllers();
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Dotnet5App", Version = "v1" });
                });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    //app.UseSwagger();
                   // app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dotnet5App v1"));
                }
    
                app.UseHttpsRedirection();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapGet("/", async context =>
                    {
                        HttpRequest request = context.Request;
                        request.EnableBuffering();   //<-- add to try to make it work
                        string message = "Unknown";
                        try
                        {
                            var reader = request.BodyReader;
                            await reader.ReadAsync();   //<-- add to try to make it work
                            message = "Content type: "   (request.ContentType == null ? "Null" : request.ContentType)   "<br>"  
                                "Request size: "   (request.ContentLength == null ? "Null" : request.ContentLength.ToString());
                        }
                        catch (Exception e)
                        {
                            message = "Error: "   e.Message;
                        }
                        await context.Response.WriteAsync(page(message));
                    });
                    
                    endpoints.MapPost("/", async context =>
                    {
                        HttpRequest request = context.Request;
                        //request.Query["query"].ToString()
                        request.EnableBuffering();   //<-- add to try to make it work
                        string message = "Unknown";
                        try
                        {
                            var reader = request.BodyReader;
                            await reader.ReadAsync();   //<-- add to try to make it work
                            message = "Content type: "   (request.ContentType == null ? "Null" : request.ContentType)   "<br>"  
                                "Request size: "   (request.ContentLength == null ? "Null" : request.ContentLength.ToString());
                        }
                        catch (Exception e)
                        {
                            message = "Error: "   e.Message;
                        }
                        await context.Response.WriteAsync(page(message));
                    });
                });
            }
            public string page(string message)
            {
                return
                    @"<html xmlns=""http://www.w3.org/1999/xhtml"">
                <meta httm-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
                <meta http-equiv=""expires"" content=""0"" />
                <title>
                TANCS TEST(PRODUCITON DATA)
                </title >
                <body>
                <form method=""post"">
                Enter a value: <input type=""text"" id="" value"" name=""query"" width=20 value=""xyz"">
                <input id=""Save"" type=""submit"">
                </form>
                "   message   @"
                </body>
                </html>";
            }
        }

Note: You may have already noticed that I have added one additional MapPost because when if you wanted to submit value using MapGet by default there will be no content type as its query string. So you need to add MapPost method for handeling submit action. Another point is method=""post"" because you are submitting post request so you need to add this method=""post"" attribute on your form request. Finally if you want to get the request size you have to set name=""query"" on your form as you can see on my code.

Additionl point is, Comment the app.UseSwagger(); and app.UseSwaggerUI so that UseSwaggerUI will not be prompted on launch page instead it will launch page method which containing the HTML file you wanted to display.

If you want to develop it further steps you can also check this enter image description here

This is the output of your code so far you have shared with us. This is how you can get the Content type and Request size using the minimal web API You can get more details in our official document here

Hope above steps guided you accordingly.

CodePudding user response:

Thank you so much (to Md Farid Uddin Kiron). Your code, with just a few changes, sends out pages, receives requests, and parses out the form variables. It is fully working. I cannot thank you enough.

Here is the full code I now have running:

Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebSite
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Startup.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Text;

namespace WebSite
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            object p = services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Dotnet5App", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseRouting();   // added, JDM
                //app.UseSwagger();
                // app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dotnet5App v1"));
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/", async context =>
                {
                    HttpRequest request = context.Request;
                    request.EnableBuffering();   //<-- add to try to make it work
                    string message = "Unknown";
                    try
                    {
                        var reader = new StreamReader(request.Body);
                        string result = await reader.ReadToEndAsync();
                        message = "Content type: "   (request.ContentType == null ? "Null" : request.ContentType)   "<br>"  
                            "Request size: "   (request.ContentLength == null ? "Null" : request.ContentLength.ToString());
                     }
                    catch (Exception e)
                    {
                        message = "Error: "   e.Message;
                    }
                    await context.Response.WriteAsync(page(message, null));
                });

                endpoints.MapPost("/", async context =>
                {
                    HttpRequest request = context.Request;
                    request.EnableBuffering();   //<-- add to try to make it work
                    string message = "Unknown";
                    Dictionary<string, string> formVariables = new Dictionary<string, string>();
                    try
                    {
                        var reader = new StreamReader(request.Body);
                        string body = await reader.ReadToEndAsync();
                        formVariables = getFormVariables(body);
                        StringBuilder display = new StringBuilder("");
                        foreach (string key in formVariables.Keys)
                        {
                            display.Append(", "   key   " = "   formVariables[key]);
                        }
                        message = "Content type: "   (request.ContentType == null ? "Null" : request.ContentType)   "<br>"  
                            "Request size: "   (request.ContentLength == null ? "Null" : request.ContentLength.ToString())   "<br>"  
                            "Form Variables: "   display.ToString().Substring(2);
                    }
                    catch (Exception e)
                    {
                        message = "Error: "   e.Message;
                    }
                    await context.Response.WriteAsync(page(message, formVariables));
                });
            });
        }
        string page(string message, Dictionary<string, string> formValues)
        {
            return
                @"<html xmlns=""http://www.w3.org/1999/xhtml"">
                <meta httm-equiv='Content-Type' content='text/html; charset=iso-8859-1' />
                <meta http-equiv=""expires"" content=""0"" />
                <title>
                TANCS TEST(PRODUCITON DATA)
                </title >
                <body>
                <form method=""post"">
                Enter a value: <input type=""text"" id="" value"" name=""query1"" width=20 value="""   FormValue(formValues, "query1")   @""">
                Enter a value: <input type=""text"" id="" value"" name=""query2"" width=20 value="""   FormValue(formValues, "query2")   @"""><br>
                <input id=""Save"" type=""submit"">
                </form>
                "   message   @"
                </body>
                </html>";
        }

        public string FormValue(Dictionary<string, string> dictionary, string key)
        {
            if (dictionary == null) return "";
            string value;
            if (!dictionary.TryGetValue(key, out value)) return "";
            return value;
        }

        public Dictionary<string, string> getFormVariables(string body)
        {
            string[] variableAssignments = body.Split('&');
            Dictionary<string, string> formVariableDictionary = new Dictionary<string, string>();
            foreach (string variableAssignment in variableAssignments)
            {
                string[] parts = variableAssignment.Split('=');
                if (parts.Length == 2) formVariableDictionary.Add(HttpUtility.UrlDecode(parts[0]), HttpUtility.UrlDecode(parts[1]));
            }
            return formVariableDictionary;
        }
    }

}
  • Related