How to return raw string with ApiController?

前端 未结 6 880
萌比男神i
萌比男神i 2020-11-29 21:49

I have an ApiController that serves XML/JSON, but I would like one of my actions to return pure HTML. I tried the below but it still return XML/JSON.

public          


        
6条回答
  •  悲&欢浪女
    2020-11-29 22:36

    I call the following webapi2 controller method from an mvc controller method:

    
    Public Function TestApiCall( 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
    

    I call it from this routine on the asp.net server:

    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
    

提交回复
热议问题