sourcetip

API 컨트롤러로 원시 문자열을 반환하는 방법은 무엇입니까?

fileupload 2023. 5. 13. 10:44
반응형

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

웹 API 작업을 반환할 수 있습니다.HttpResponseMessage내용을 완전히 제어할 수 있습니다.이 경우 StringContent를 사용하고 올바른 컨텐츠 유형을 지정할 수 있습니다.

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

또는

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

또 다른 가능한 해결책.웹 API 2에서 저는 베이스를 사용했습니다.의 내용() 메서드APIController:

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

JSON 콘텐츠를 계속 다운로드하려는 IE9 버그를 피하기 위해 이 작업을 수행해야 했습니다.이것은 또한 다음을 사용하여 XML 유형 데이터에 대해서도 작동해야 합니다.XmlMediaTypeFormatter미디어 포맷터

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

그저.return Ok(value)작동하지 않습니다. 다음과 같이 위협할 것입니다.IEnumerable<char>.

대신 사용return Ok(new { Value = value })또는 그와 유사합니다.

웹이 아닌 MVC를 사용하는 경우베이스를 사용할 수 있는 API입니다.내용 방법:

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

저는 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

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

반응형