Programing

Asp.net WEBAPI에서 명시 적으로 JSON 문자열을 반환합니까?

lottogame 2020. 9. 20. 10:29
반응형

Asp.net WEBAPI에서 명시 적으로 JSON 문자열을 반환합니까?


어떤 경우에는 NewtonSoft JSON.NET이 있고 컨트롤러에서 컨트롤러에서 Jobject를 반환하고 모두 좋습니다.

하지만 다른 서비스에서 원시 JSON을 가져 와서 내 webAPI에서 반환해야하는 경우가 있습니다. 이 맥락에서 나는 NewtonSOft를 사용할 수 없지만, 만약 내가 할 수 있다면 문자열 (불필요한 처리 오버 헤드처럼 보이는)에서 JOBJECT를 생성하고 그것을 반환하면 모든 것이 세상에 잘 될 것입니다.

그러나 이것을 간단히 반환하고 싶지만 문자열을 반환하면 클라이언트는 내 컨텍스트가 인코딩 된 문자열로 JSON 래퍼를받습니다.

WebAPI 컨트롤러 메서드에서 JSON을 명시 적으로 반환하려면 어떻게해야합니까?


몇 가지 대안이 있습니다. 가장 간단한 방법은 메서드가를 반환 하도록하고 아래 코드와 유사한 문자열을 기반으로하여 HttpResponseMessage해당 응답을 만드는 것입니다 StringContent.

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return response;
}

null 또는 빈 JSON 문자열 확인

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    if (!string.IsNullOrEmpty(yourJson))
    {
        var response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
        return response;
    }
    throw new HttpResponseException(HttpStatusCode.NotFound);
}

다음은 WebApi2에 도입 된 IHttpActionResult 인터페이스를 사용하도록 조정 된 @carlosfigueira의 솔루션입니다.

public IHttpActionResult Get()
{
    string yourJson = GetJsonFromSomewhere();
    if (string.IsNullOrEmpty(yourJson)){
        return NotFound();
    }
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return ResponseMessage(response);
}

WebAPI 기능 (예 : XML 허용)을 사용하지 않고 해당 JSON 만 반환하려는 경우 항상 출력에 직접 쓸 수 있습니다. ASP.NET으로 이것을 호스팅한다고 가정하면 Response개체에 대한 액세스 권한이 있으므로 문자열로 작성할 수 있으므로 실제로 메서드에서 아무것도 반환 할 필요가 없습니다. 출력 스트림에 대한 응답 텍스트.


웹 API GET 메서드에서 json 데이터를 반환하는 샘플 예제

[HttpGet]
public IActionResult Get()
{
            return Content("{\"firstName\": \"John\",  \"lastName\": \"Doe\", \"lastUpdateTimeStamp\": \"2018-07-30T18:25:43.511Z\",  \"nextUpdateTimeStamp\": \"2018-08-30T18:25:43.511Z\");
}

참고URL : https://stackoverflow.com/questions/17097841/return-a-json-string-explicitly-from-asp-net-webapi

반응형