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

 

转载于:https://www.cnblogs.com/ToughGuy/p/5157113.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值