'Returning a Task in app.GetMap() function
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.
Solution 1:[1]
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.
Solution 2:[2]
Do something like this:
Task.FromResult(context.Request.Headers["User-Agent"].ToString());
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 | Mohammad Mirmostafa |
| Solution 2 | Mohammad Mirmostafa |

