有没有办法强制 ASP.NET Web API 返回纯文本? [英] Is there a way to force ASP.NET Web API to return plain text?

查看:21
本文介绍了有没有办法强制 ASP.NET Web API 返回纯文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 ASP.NET Web API 控制器以纯文本形式返回响应.

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

我试过用 Accept: text/plain 做一个请求,但它似乎没有成功.此外,请求是外部的,不受我控制.我要完成的是模仿旧的 ASP.NET 方式:

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

有什么想法吗?

编辑,解决方案:根据 Aliostad 的回答,我添加了 WebAPIContrib 文本格式化程序,并在 Application_Start 中对其进行了初始化:

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

推荐答案

嗯...我认为您不需要创建自定义格式化程序来完成这项工作.而是像这样返回内容:

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.

如果您明确想要创建输出并覆盖基于 Accept 标头的默认内容协商,您将不想使用 Request.CreateResponse(),因为它强制使用 mime 类型.

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.

而是显式创建一个新的 HttpResponseMessage 并手动分配内容.上面的示例使用 StringContent,但还有很多其他内容类可用于从各种 .NET 数据类型/结构返回数据.

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.

这篇关于有没有办法强制 ASP.NET Web API 返回纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆