Friday 19 March 2021

Return a JSON string explicitly from Asp.net WEBAPI? or api return string as json in asp net web

 /////// 

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


Normal Code >>

        public HttpResponseMessage GetEmployees()
        {
            DataTable dt = new DataTable();
            var item = JsonConvert.SerializeObject(dt);            
            if (item != null && !string.IsNullOrEmpty(item))
            {               
                return Request.CreateResponse(HttpStatusCode.OK, item);
            }
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

Method >1.

public HttpResponseMessage Get() {

            string yourJson = GetJsonFromSomewhere();

            var response = this.Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");

            return response;

        }


Method >2.


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

        }



No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...