Search code examples
c#asp.netasp.net-web-apiasp.net-web-api2

Web API 2 return simple string without quotation mark when return type is IHttpActionResult


My question is referring to this question.

The answer shows only solutions where you would have to change the type of the method to HttpResponseMessage or string.

This is my method:

public IHttpActionResult Get()
{
    return Ok("I am send by HTTP resonse");
}

It returns:

"I am send by HTTP resonse"

I expect:

I am send by HTTP response

Is there a way to return a simple string without quotation mark where the return type of the method is IHttpActionResult?


Solution

  • You can use ApiController.ResponseMessage(HttpResponseMessage) Method

    Creates a ResponseMessageResult with the specified response.

    ResponseMessageResult is derived from IHttpActionResult

    public IHttpActionResult Get() {
        var message = "I am send by HTTP response";
        var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) {
            Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain")
        };
        return ResponseMessage(httpResponseMessage);
    }