Return a JSON string explicitly from Asp.net WEBAPI?

前端 未结 6 1248
栀梦
栀梦 2020-11-27 03:30

In Some cases I have NewtonSoft JSON.NET and in my controller I just return the Jobject from my controller and all is good.

But I have a case where I get some raw JS

6条回答
  •  無奈伤痛
    2020-11-27 04:08

    There are a few alternatives. The simplest one is to have your method return a HttpResponseMessage, and create that response with a StringContent based on your string, something similar to the code below:

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

    And checking null or empty JSON string

    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);
    }
    

提交回复
热议问题