mvc、webapi杂记


//1、JsonSerializerSettings
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss",//用于WebAPI日期序列化
};

//2、禁用格式化器
    // Remove the JSON formatter

    // 删除JSON格式化器
    config.Formatters.Remove(config.Formatters.JsonFormatter);
// or(或者)
// Remove the XML formatter // 删除XML格式化器 config.Formatters.Remove(config.Formatters.XmlFormatter);


//3、解决MvcJsonResult返回的Date格式化(/Date(1359522345000)/),以继承折方式重写即可。
//http://www.cnblogs.com/JerryWang1991/archive/2013/03/08/2950457.html

 

//4、WebApi全局异常处理

config.Filters.Add(new WebApiExceptionFilter());

public partial class WebApiExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var Ex = context.Exception;

            //增加二行 Trace 代码
            Trace.TraceError("异常: {0}", Ex.Message);
            Trace.TraceError("请求 URI: {0}", context.Request.RequestUri);

            var message = Ex.Message;
            if (Ex.InnerException != null)
                message = Ex.InnerException.Message;

            //注意:ResponseException不会来
            if (Ex is NotImplementedException)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.NotImplemented, new HttpError("此方法暂未实现"));
            }
            else if (Ex is InvalidOperationException)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError("未将对象引用设置到对象的实例,可能存在无效参数"));
            }
            else if (Ex is NotFondException)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.NotFound, new HttpError("所需实例不存在"));
            }
            else if (Ex is PageSizeException)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.NotFound, new HttpError(Ex.Message));
            }
            else if (Ex is ExException)
            {
                var ExEx = Ex as ExException;
                context.Response = context.Request.CreateResponse(HttpStatusCode.BadRequest, new JsonRet(ExEx.Code, ExEx.Message,ExEx.Object));
            }
            else
            {

                if (Ex.Message.Contains("String or binary data would be truncated."))
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.NotFound, new HttpError("可能存在字段的字符超长!"));
                }
                else
                {

                    context.Response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, new HttpError(Ex.Message));

                }
            }
            base.OnException(context);
        }
    }
View Code

 

//5、数据注解-模型验证
GlobalConfiguration.Configuration.Filters.Add(new ModelValidationFilterAttribute());

    // Model验证
    public class ModelValidationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            var modelState = context.ModelState;
            if (modelState.IsValid == false)
            {

                //返回多个

                var errors = new List<object>();
                foreach (var state in modelState)
                {


                    if (state.Value.Errors.Count > 0)
                    {

                        var ErrorMessage = state.Value.Errors[0].ErrorMessage;
                        if (string.IsNullOrEmpty(ErrorMessage))
                        {
                            var Message = state.Value.Errors[0].Exception.Message;

                            if (Message.Contains("Could not convert "))
                            {
                                Message = "参数格式错误,请重新录入!";
                            }

                            errors.Add(new { Success = false, Code = -1, Key = state.Key, Message = Message });
                        }
                        else
                        {
                            errors.Add(new { Success = false, Code = -1, Key = state.Key, Message = ErrorMessage });
                        }
                    }
                    else
                    {

                    }
                }

                context.Response = context.Request.CreateResponse(HttpStatusCode.OK, errors.Count > 0 ? errors[0] : null);
            }
        }
    }
View Code

 

posted @ 2016-01-25 12:31  胡 杨  阅读(303)  评论(0编辑  收藏  举报