.NET Web API / MVC Request Body
A shortie but a goodie
Ever want to look at the request body, the request headers and so on in .NET Web API ?
Well, that doesn't exactly tell you how to do it. In fact, nothing does. Microsoft wants you to work at a higher level of abstraction than looking at the request. But we all know that isn't always a good idea or possible. Time to quit back to NodeJS?
If you look at Stack Overflow you will see many answers like this
string result = await Request.Content.ReadAsStringAsync();
One problem. It doesn't actually work.
* It might return an empty string
* It might hang the application
* It can deadlock
* Evil happens
So don't do it
What do you do instead?
Well, not to worry there is actually a very simple answer that's so simple it should be in the Microsoft examples (but it isn't). Hundreds or thousands of hours of experience and debugging contributed to finding this answer (or one lucky StackOverflow post you choose what to believe). You could look for this answer for ten sprints and not find it.
You will now receive this answer.
public HttpResponseMessage Get(HttpRequestMessage message)
{
// Access the message body here!
var content = message.Content.ReadAsStringAsync();
Task.WaitAll(content);
var body = content.Result;
}
With great power comes great responsibility -- take a deep dive into Tasks (and Microsoft in general) in this man's blog here https://blog.stephencleary.com/2014/04/a-tour-of-task-part-0-overview.html but for those who just need to access the request body (which in NodeJS takes two seconds) the above should work
Of course ask yourself the question if you really want to use the Request Body. If you really need it.
Happy Coding!
No comments:
Post a Comment