I’m trying to write a simple string from the user-agent request headers in to the browser.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", (context) => return context.Request.Headers["User-Agent"].ToString(););
app.Run();
This gives a compile error Cannot convert expression type 'string' to return type 'System.Threading.Tasks.Task'
.
What is the proper solution to this. From what I understand I need to wrap the string context.Request.Headers["User-Agent"].ToString();
with a Task but i don’t really know how to do this properly inside the arrow function.
2
Answers
Do something like this:
This will work:
app.MapGet("/", (HttpContext context) => context.Request.Headers["User-Agent"].ToString());
It’s because the name of parameter is not important. If you look at the picture, you can see the compiler supposes that the parameter is a
HttpRequest
, not aHttpContext
.