Three unified framework before and after the end of the separation structures scratch NetCore (EF Core CodeFirst + Au) + Vue return data items

In the  previous  talked about how the DbContext and decoupling model through autofac, only add model, without adding DbSet in DbContext in. We talked about how this one will return to the back-end unified data model.

First we have to understand in general what some of the backend data should be returned to the front. According to my contact with their usual open platform interface and involved knowledge.

Probably summed up a few points, there are gains and return of the status code, the second must have a return status information, the three have to have the data values ​​returned.

If that is the case there is an error, it should return an error model, error model includes error coding and error introduction. Error code is to provide an interface for people to use to find the error code solution, error Profile is told it is probably what wrong.

This section need to use a static extension method previously packaged, transfer gate   please choose to add! !

  1. Under the new project CoreMvc return model class  ResponseResult  reads as follows:
    /// <inheritdoc />
        /// <summary>
        /// 响应返回体
        /// </summary>
        public class ResponseResult : ResponseResult<object>
        {
        }
        /// <summary>
        /// 响应返回体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class ResponseResult<T> : BaseResponseResult
        {
            public T Data { get; set; }
    
            public ResponseResult<T> Fail(int code, string msg, T data)
            {
                Code = code;
                Message = msg;
                Data = data;
                return this;
            }
    
            public ResponseResult<T> Succeed(T data, int code = 200, string msg = "successful")
            {
                Code = code;
                Message = msg;
                Data = data;
                return this;
            }
        } 
        Public  class BaseResponseResult 
        { 
            public  int Code { GET ; SET ;} 
    
            public  String the Message { GET ; SET ;} 
    
            public  BOOL Success => == Code 200 ; // custom successful status code 200 
        }
    View Code
  2. New Custom Json result is returned to the front end of the class data  CustomJsonResult  , inheritance need  ActionResult  follows:
    /// <summary>
        /// 自定义返回Json数据
        /// </summary>
        public class CustomJsonResult : ActionResult
        {
            public object Data { get; set; }
    
            public string DateTimeFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
    
    
            public override void ExecuteResult(ActionContext context)
            {
                if (context == null)
                    throw new ArgumentNullException(nameof(context));
                var response = context.HttpContext.Response;
                response.ContentType = "application/json";
                if (Data == null) return;
                if (string.IsNullOrEmpty(DateTimeFormat))
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                }
                string json;
    #if DEBUG
                json = Data.ToJson(true, true, true, DateTimeFormat);//方便调式
    #else
                json = Data.ToJson(true, false, true, DateTimeFormat);
    #endif
                var data = Encoding.UTF8.GetBytes(json);
                response.Body.Write(data, 0, data.Length);
            }
        }
    View Code
  3. New Custom Json result data returned to the front end of the class (including the HTTP status code)  CustomHttpStatusCodeResult  , inheritance need  ActionResult  follows:
    /// <summary>
        /// 返回带有HTTP状态码的json结果
        /// </summary>
        public class CustomHttpStatusCodeResult : ActionResult
        {
    
            public int StatusCode { get; }
    
            public string Data { get; }
    
            public CustomHttpStatusCodeResult(int httpStatusCode, int msgCode, string content = "", object data = null)
            {
                StatusCode = httpStatusCode;
                Data = new ResponseResult().Fail(msgCode, content ?? "", data ?? "").ToJson(true, isLowCase: true);
            }
    
            public override void ExecuteResult(ActionContext context)
            {
                if (context == null)
                    throw new ArgumentNullException(nameof(context));
                context.HttpContext.Response.StatusCode = StatusCode;
                if (string.IsNullOrEmpty(Data))
                    return;
                context.HttpContext.Response.ContentType = "application/json";
                var bytes = Encoding.UTF8.GetBytes(Data);
    
                context.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
            }
        }
    View Code
  4. New  BaseController  used to encapsulate the data and returns the acquisition parameters or the like, for an inherited  Controller  as follows:
    public abstract class BaseController : Controller
        {
            /// <summary>
            /// 从 Request.Body 中获取数据并JSON序列化成对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            protected T GetJsonParams<T>()
            {
                if (Request.ContentLength != null)
                {
                    var bytes = new byte[(int)Request.ContentLength];
                    Request.Body.Read(bytes, 0, bytes.Length);
                    var json = Encoding.UTF8.GetString(bytes);
                    return json.ToNetType<T>();
                }
    
                return default(T);
            }
    
            /// <summary>
            /// 返回Json数据
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            protected ActionResult MyJson(BaseResponseResult data)
            {
                return new CustomJsonResult
                {
                    Data = data,
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss" 
                }; 
            } 
    
            ///  <Summary> 
            /// Returns Success
             /// Json format
             ///  </ Summary> 
            ///  <Returns> </ Returns> 
            protected ActionResult Succeed () 
            { 
                return Succeed ( to true ); 
            } 
    
            ///  <Summary> 
            /// returns success
             /// Json format
             ///  </ Summary> 
            ///  <param name = "Data"> </ param> 
            ///  <returns> </ returns>
            protected ActionResult Succeed(object data)
            {
                return MyJson(new ResponseResult().Succeed(data));
            }
    
            [ApiExplorerSettings(IgnoreApi = true)]
            public ActionResult Fail(int code, string content = "", string desc = null)
            {
                return MyJson(new ResponseResult().Fail(code, content + " " + desc, "")
               );
            }
    
            [ApiExplorerSettings(IgnoreApi = true)]
            public override void OnActionExecuting(ActionExecutingContext context)
            {
                base.OnActionExecuting(context);
            }
    
            [ApiExplorerSettings(IgnoreApi = true)]
            public override void OnActionExecuted(ActionExecutedContext context)
            {
    
            }
        }
    View Code

     

Here we have basically been completed the unification of the returned data, and inherit on each controller  BaseController  class, and then return data when used directly.

  1. return Succeed ( new new String [] { " VALUE1 " });  returns a success message.
  2. return the Fail ( 1001 , " error is returned exemplary " ); // 1001 for their own custom error code  returns an error message
  3. var Response = new new ResponseResult (); response.Succeed ( " success message " ); return MyJson (Response);  custom needs to return results
  4. var requestStr = GetJsonParams < String > ();  can be used to retrieve data from this statement request the Body, easy to use.
    Corresponding model can also be defined using  [FromBody]  acquired from the request the Body: The  [FromBody] DemoModel Demo  , the front end of the transmission data: {Id: 1, CustomerName:

  

  It describes how to use a lower filter will be global exception handler, or custom exception handling exception thrown those untreated.

 

  Need source code under comments or private letter to me ~ SVN guest account password to download the code is not on GitHub.

Guess you like

Origin www.cnblogs.com/levywang/p/coreframe_3.html