Programming

ApiController로 원시 문자열을 반환하는 방법은 무엇입니까?

procodes 2020. 7. 18. 23:16
반응형

ApiController로 원시 문자열을 반환하는 방법은 무엇입니까?


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 태그 없이도 이스케이프 처리되지 않은 순수한 텍스트 만 반환하는 방법이 있습니까 (다른 반환 유형의 작업 특성 일 수 있음)?


귀하는 Web Api 조치가 귀하 HttpResponseMessage가 컨텐츠를 완전히 제어 할 수 있는를 리턴하도록 할 수 있습니다. 귀하의 경우 StringContent를 사용하고 올바른 컨텐츠 유형을 지정할 수 있습니다.

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

또 다른 가능한 해결책. Web API 2에서 나는 base.Content () 메소드를 사용했습니다 APIController:

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

JSON 콘텐츠를 계속 다운로드하려고하는 IE9 버그를 피하려면이 작업을 수행해야했습니다. XmlMediaTypeFormatter미디어 포맷터 를 사용하여 XML 유형 데이터에도 적용됩니다 .

누군가에게 도움이되기를 바랍니다.


다만 return Ok(value)그것은으로 간주됩니다 작동하지 않습니다 IEnumerable<char>.

대신 사용 return Ok(new { Value = value })하거나 비슷하게 사용하십시오 .


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

WebAPI 대신 MVC를 사용하는 경우 base.Content 메소드를 사용할 수 있습니다.

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

우리는 API에서 HTML이 아닌 순수한 데이터를 반환하지 않고 UI에 따라 데이터를 형식화하려고 노력해야하지만 다음을 사용할 수 있습니다.

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

그것은 나를 위해 작동

참고 URL : https://stackoverflow.com/questions/14046417/how-to-return-raw-string-with-apicontroller

반응형