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

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

问题描述

我需要得到回应回来从的ASP.NET Web API控制器纯文本。

我曾尝试做请求接受:纯文本/ ,但它似乎并没有这样的伎俩。
此外,该请求是外部的,在我的掌握。我会做到的是模仿老的ASP.NET方式:

  context.Response.ContentType =text / plain的;
context.Response.Write(一些文本);

任何想法?

编辑,解决方案的:
基于Aliostad的回答,我添加了 WebAPIContrib 文本格式,在Application_Start初始化它:

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

和我的控制器最终是这样的:

  [HTTPGET,HttpPost]
公众的Htt presponseMessage GetPlainText()
{
  返回ControllerContext.Request.CreateResponse(的HTTPStatus code.OK,测试数据,text / plain的);
}


解决方案

嗯...我不认为你需要创建一个自定义的格式,使这项工作。相反,返回的内容是这样的:

  [HTTPGET]
    公众的Htt presponseMessage的HelloWorld()
    {
        字符串结果=你好!世界时间是:+ DateTime.Now;
        VAR RESP =新的Htt presponseMessage(的HTTPStatus code.OK);
        resp.Content =新的StringContent(结果,System.Text.Encoding.UTF8,text / plain的);
        返回RESP;
    }

这对我的作品,而无需使用自定义格式。

如果要明确根据接受你不会想使用页眉创造产出和覆盖缺省内容协商 Request.CreateResponse(),因为它迫使哑剧类型。

而是明确创建一个新的的Htt presponseMessage 和手动分配的内容。上述用途的例子的StringContent 但也有不少其他内容可从不同的.NET数据类型/结构返回数据类。

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

解决方案

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.

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

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