Read content body from a HTTP GET in C# WebAPI

2019-09-06 10:17发布

问题:

I have a WebAPI C# application. My GET method is defined as:

[HttpGet]
public HttpResponseMessage Get(string id)

This API retrieves some content from a database, based on a given id. Another parameter is required but it is so long that having it on the URL would not work, so I'm using the GET body to send such second parameter.

How can I retrieve it from inside the get method?

I tried

var dataOnBody = await Request.Content.ReadAsStringAsync();

but it doesn't work as the Get method is not async and I think it doesn't need to be that (I want a normal blocking function which reads the content of the body and outputs a string)

I just need a simple way to extract my string from the request body

回答1:

Even if you somehow manage to do this, you will find that support is not universal. The HTTP specs say:

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

So the data returned relies only on the URI, not anything in the body. Many libraries won't even let you send a request body during a GET.