Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

Is there a way to force ASP.NET Web API to return plain text?

I need to get a response back in plain text from a ASP.NET Web API controller.

I have tried do a request with Accept: text/plain but it doesn't seem to do the trick. Besides, the request is external and out of my control. What I would accomplish is to mimic the old ASP.NET way:

context.Response.ContentType = "text/plain";
context.Response.Write("some text);

Any ideas?

EDIT, solution: Based on Aliostad's answer, I added the WebAPIContrib text formatter, initialized it in the Application_Start:

  config.Formatters.Add(new PlainTextFormatter());

and my controller ended up something like:

[HttpGet, HttpPost]
public HttpResponseMessage GetPlainText()
{
  return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "Test data", "text/plain");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hmmm... I don't think you need to create a custom formatter to make this work. Instead return the content like this:

    [HttpGet]
    public HttpResponseMessage HelloWorld()
    {
        string result = "Hello world! Time is: " + DateTime.Now;
        var resp = new HttpResponseMessage(HttpStatusCode.OK);
        resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
        return resp;
    }

This works for me without using a custom formatter.

If you explicitly want to create output and override the default content negotiation based on Accept headers you won't want to use Request.CreateResponse() because it forces the mime type.

Instead explicitly create a new HttpResponseMessage and assign the content manually. The example above uses StringContent but there are quite a few other content classes available to return data from various .NET data types/structures.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...