Web Api: recommended way to return json string

前端 未结 4 790
一个人的身影
一个人的身影 2020-12-10 15:57

I\'ve got a couple of services which already receive a json string (not an object) that must be returned to the client. Currently, I\'m creating the HttpResponseMessag

4条回答
  •  不知归路
    2020-12-10 16:25

    Set your Web Api to return JSON Format:

        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            // Force to ignore Request Content Type Header and reply only JSON
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
    
            var corsAttr = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(corsAttr);
        }
    

    and then return response like this:

            [HttpGet]
        [Route("{taskId}/list")]
        public IHttpActionResult GetTaskDocuments(string taskId)
        {
            var docs = repository.getTaskDocuments(taskId);
            if (docs != null)
            {
                return Ok(docs);
            }
            else
            {
                return Ok(new ResponseStatus() { Status = Constants.RESPONSE_FAIL, Message = repository.LastErrorMsg });
            }
        }
    

    Where ResponseStatus is next class:

     public class ResponseStatus
        {
            public string Status { get; set; }
            public string Message { get; set; }
        }
    

提交回复
热议问题