• ASP.NET Core小技巧(自定义路由、全局异常处理、日期时间格式设置、空处理)


    1.自定义路由
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
     
                #region 自定义路由配置
                app.UseMvc(routes =>
                {
                    // 自定义路由
                    routes.MapRoute(
                      name: "default1",
                      template: "api/{controller}/{action}/{id?}",
                      defaults: new { controller = "Values", action = "Index" });
                    // 默认路由
                    routes.MapRoute(
                       name: "default",
                       template: "{controller}/{action}/{id?}",
                       defaults: new { controller = "Values", action = "Index" });
                });
                #endregion
            }

    2.允许跨域设置

    public void ConfigureServices(IServiceCollection services)
            {
                #region 跨域设置
                services.AddCors(options =>
                {
                    options.AddPolicy("AppDomain", builder =>
                    {
                   builder.AllowAnyOrigin() // Allow access to any source from the host
                   AllowAnyMethod()        // Ensures that the policy allows any method
                   AllowAnyHeader()        // Ensures that the policy allows any header
                   .AllowCredentials();     // Specify the processing of cookie
                    });
                });
                #endregion
                services.AddMvc();
            }
    3.json数据,string类型字段返回为null时默认返回空字符串
    public sealed class NullWithEmptyStringResolver : DefaultContractResolver
        {
            protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
            {
                return type.GetProperties()
                           .Select(p =>
                           {
                               var jp = base.CreateProperty(p, memberSerialization);
                               jp.ValueProvider = new NullToEmptyStringValueProvider(p);
                               return jp;
                           }).ToList();
            }
     
            /// <summary>
            /// 将所有返回字段转换为小写
            /// </summary>
            /// <param name="propertyName"></param>
            /// <returns></returns>
            //protected override string ResolvePropertyName(string propertyName)
            //{
            //    return propertyName.ToLower();
            //}
        }
     
        public class NullToEmptyStringValueProvider : IValueProvider
        {
            PropertyInfo _MemberInfo;
            public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
            {
                _MemberInfo = memberInfo;
            }
     
            public object GetValue(object target)
            {
                object result = _MemberInfo.GetValue(target);
                if (result == null)
                {
                    var type = _MemberInfo.PropertyType;
                    if (type == typeof(string)) result = "";
                    //else if (type == typeof(DateTime?))
                    //    result = new DateTime(1, 1, 1);
                }
                return result;
            }
     
            public void SetValue(object target, object value)
            {
                _MemberInfo.SetValue(target, value);
            }
    }
     
     
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().AddJsonOptions(options =>
                   {
                       options.SerializerSettings.Formatting = Formatting.Indented;  // 返回数据格式缩进(按需配置)
                       options.SerializerSettings.ContractResolver = new NullWithEmptyStringResolver();  // 字段为字符串返回为null时,默认返回空
                   });
            }
    4.json数据,自定义日期格式
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().AddJsonOptions(options =>
                   {
                       options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 日期格式化
                   });

    5.Asp.net Core WebApi 全局异常类

    1、自定义一个全局异常处理类中间件
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    using UFX.Mall.EntityModel;
    using UFX.Tools;
     
    namespace UFX.Mall.WebApi
    {
        public class ExceptionHandlerMiddleWare
        {
            private readonly RequestDelegate next;
     
            public ExceptionHandlerMiddleWare(RequestDelegate next)
            {
                this.next = next;
            }
     
            public async Task Invoke(HttpContext context)
            {
                try
                {
                    await next(context);
                }
                catch (Exception ex)
                {
                    await HandleExceptionAsync(context, ex);
                }
            }
     
            private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
            {
                if (exception == null) return;
                await WriteExceptionAsync(context, exception).ConfigureAwait(false);
            }
     
            private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
            {
                //记录日志
                LogHelper.Error(exception.GetBaseException().ToString());
               
                //返回友好的提示
                var response = context.Response;
     
                //状态码
                if (exception is UnauthorizedAccessException)
                    response.StatusCode = (int)HttpStatusCode.Unauthorized;
                else if (exception is Exception)
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
     
                response.ContentType = context.Request.Headers["Accept"];
     
                if (response.ContentType.ToLower() == "application/xml")
                {
                    await response.WriteAsync(Object2XmlString(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false);
                }
                else
                {
                    response.ContentType = "application/json";
                    await response.WriteAsync(JsonConvert.SerializeObject(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false);
                }
            }
     
            /// <summary>
            /// 对象转为Xml
            /// </summary>
            /// <param name="o"></param>
            /// <returns></returns>
            private static string Object2XmlString(object o)
            {
                StringWriter sw = new StringWriter();
                try
                {
                    XmlSerializer serializer = new XmlSerializer(o.GetType());
                    serializer.Serialize(sw, o);
                }
                catch
                {
                    //Handle Exception Code
                }
                finally
                {
                    sw.Dispose();
                }
                return sw.ToString();
            }
     
        }
    }
    2、configure注册
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
                //配置NLog
                loggerFactory.AddNLog();
                env.ConfigureNLog("nlog.config");
     
                app.UseApplicationInsightsRequestTelemetry();
     
                app.UseApplicationInsightsExceptionTelemetry();
     
                //异常处理中间件
                app.UseMiddleware(typeof(ExceptionHandlerMiddleWare));
     
                app.UseMvc(); ;
            }
  • 相关阅读:
    Leetcode:Convert Sorted List to Binary Search Tree
    Leetcode:Unique Binary Search Trees & Unique Binary Search Trees II
    Leetcode::Longest Common Prefix && Search for a Range
    Leetcode::Flatten Binary Tree to Linked List
    Leetcode::JumpGame
    leetcode power(x,n)
    Leetcode Letter Combinations of a Phone Number
    leetcode Reverse Nodes in k-Group
    leetcode Merge k Sorted Lists
    word ladder
  • 原文地址:https://www.cnblogs.com/hobelee/p/13972687.html
Copyright © 2020-2023  润新知