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

Viewed 1593

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?

3 Answers

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);
}

Change it to:

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

The IHttpActionResult is WebApi2 way, you can also use

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I am send by HTTP response");
}

Also if you expect without double quotes please refer to the link you specified in your question.

Related