skip to Main Content

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


  1. Do something like this:

    Task.FromResult(context.Request.Headers["User-Agent"].ToString());
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search