Home > Enterprise >  Returning a Task in app.GetMap() function
Returning a Task in app.GetMap() function

Time:03-28

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.

CodePudding user response:

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 a HttpContext.

enter image description here

CodePudding user response:

Do something like this:

Task.FromResult(context.Request.Headers["User-Agent"].ToString());
  • Related