Return content with IHttpActionResult for non-OK response

前端 未结 15 2171
北恋
北恋 2020-11-28 17:55

For returning from a Web API 2 controller, I can return content with the response if the response is OK (status 200) like this:

    public IHttpActionResult          


        
15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 18:38

    Above things are really helpful.

    While creating web services, If you will take case of services consumer will greatly appreciated. I tried to maintain uniformity of the output. Also you can give remark or actual error message. The web service consumer can only check IsSuccess true or not else will sure there is problem, and act as per situation.

      public class Response
        {
            /// 
            /// Gets or sets a value indicating whether this instance is success.
            /// 
            /// 
            /// true if this instance is success; otherwise, false.
            /// 
            public bool IsSuccess { get; set; } = false;
    
            /// 
            /// Actual response if succeed 
            /// 
            /// 
            /// Actual response if succeed 
            /// 
            public object Data { get; set; } = null;
    
            /// 
            /// Remark if anythig to convey
            /// 
            /// 
            /// Remark if anythig to convey
            /// 
            public string Remark { get; set; } = string.Empty;
            /// 
            /// Gets or sets the error message.
            /// 
            /// 
            /// The error message.
            /// 
            public object ErrorMessage { get; set; } = null;
    
    
        }  
    
    
    
    
    [HttpGet]
            public IHttpActionResult Employees()
            {
                Response _res = new Response();
                try
                { 
                    DalTest objDal = new DalTest(); 
                    _res.Data = objDal.GetTestData();
                    _res.IsSuccess = true;
                    return Ok(_res);
                }
                catch (Exception ex)
                {
                    _res.IsSuccess = false;
                    _res.ErrorMessage = ex;
                    return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, _res )); 
                } 
            }
    

    You are welcome to give suggestion if any :)

提交回复
热议问题