'Cannot get basic request/response in .NET 5 web site to work
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>";
}
Solution 1:[1]
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;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jon Melvin |
