如何使用ApiController返回原始字符串?

时间:2012-12-26 21:21:50

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我有一个提供XML / JSON的ApiController,但我希望我的一个动作可以返回纯HTML。我尝试了以下但它仍然返回XML / JSON。

public string Get()
{
    return "<strong>test</strong>";
}

这就是上面的回报:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;strong&gt;test&lt;/strong&gt;</string>

有没有办法只返回纯粹的未转义文本,甚至没有周围的XML标签(可能是不同的返回类型的action属性)?

6 个答案:

答案 0 :(得分:202)

您可以让您的Web Api操作返回HttpResponseMessage,您可以完全控制内容。在您的情况下,您可以使用StringContent并指定正确的内容类型:

public HttpResponseMessage Get()
{
    return new HttpResponseMessage()
    {
        Content = new StringContent(
            "<strong>test</strong>", 
            Encoding.UTF8, 
            "text/html"
        )
    };
}

答案 1 :(得分:6)

另一种可能的解决方案。在Web API 2中,我使用了APIController的base.Content()方法:

    public IHttpActionResult Post()
    {
        return base.Content(HttpStatusCode.OK, new {} , new JsonMediaTypeFormatter(), "text/plain");
    }

我需要这样做以解决IE9错误,它一直试图下载JSON内容。这也适用于使用XmlMediaTypeFormatter媒体格式化程序的XML类型数据。

希望能有所帮助。

答案 2 :(得分:3)

只是return Ok(value)无法工作,它将被视为IEnumerable<char>

而是使用return Ok(new { Value = value })或simillar。

答案 3 :(得分:0)

我从mvc控制器方法调用以下webapi2控制器方法:

<HttpPost>
Public Function TestApiCall(<FromBody> screenerRequest As JsonBaseContainer) As IHttpActionResult
    Dim response = Me.Request.CreateResponse(HttpStatusCode.OK)
    response.Content = New StringContent("{""foo"":""bar""}", Encoding.UTF8, "text/plain")
    Return ResponseMessage(response)
End Function

我在asp.net服务器上通过这个例程调用它:

Public Async Function PostJsonContent(baseUri As String, requestUri As String, content As String, Optional timeout As Integer = 15, Optional failedResponse As String = "", Optional ignoreSslCertErrors As Boolean = False) As Task(Of String)
    Return Await PostJsonContent(baseUri, requestUri, New StringContent(content, Encoding.UTF8, "application/json"), timeout, failedResponse, ignoreSslCertErrors)
End Function

Public Async Function PostJsonContent(baseUri As String, requestUri As String, content As HttpContent, Optional timeout As Integer = 15, Optional failedResponse As String = "", Optional ignoreSslCertErrors As Boolean = False) As Task(Of String)
    Dim httpResponse As HttpResponseMessage

    Using handler = New WebRequestHandler
        If ignoreSslCertErrors Then
            handler.ServerCertificateValidationCallback = New Security.RemoteCertificateValidationCallback(Function(sender, cert, chain, policyErrors) True)
        End If

        Using client = New HttpClient(handler)
            If Not String.IsNullOrWhiteSpace(baseUri) Then
                client.BaseAddress = New Uri(baseUri)
            End If

            client.DefaultRequestHeaders.Accept.Clear()
            client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
            client.Timeout = New TimeSpan(TimeSpan.FromSeconds(timeout).Ticks)

            httpResponse = Await client.PostAsync(requestUri, content)

            If httpResponse.IsSuccessStatusCode Then
                Dim response = Await httpResponse.Content.ReadAsStringAsync
                If Not String.IsNullOrWhiteSpace(response) Then
                    Return response
                End If
            End If
        End Using
    End Using

    Return failedResponse
End Function

答案 4 :(得分:0)

如果您使用的是MVC而不是WebAPI,则可以使用base.Content方法:

return base.Content(result, "text/html", Encoding.UTF8);

答案 5 :(得分:-1)

我们必须努力不在UI中返回html,而是从我们的API返回纯数据并格式化数据,但也许你可以使用:

return this.Request.CreateResponse(HttpStatusCode.OK, 
     new{content=YourStringContent})

它对我有用