C# ASP.NET WebApi入门

1.创建一个WebApi项目

1️⃣VS2019 创建ASP.NET应用程序
在这里插入图片描述
2️⃣注意:框架要选择.NETF FrameWork 4.5及以上在这里插入图片描述在这里插入图片描述
文件目录如下
在这里插入图片描述
End创建结束

测试Demo

1.创建实体类

public partial class UserInfo
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 用户姓名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 用户密码
        /// </summary>
        public string UserPass { get; set; }
        /// <summary>
        /// 注册时间
        /// </summary>
        public System.DateTime RegTime { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }
    }

2.创建ApiController在这里插入图片描述

		[HttpGet]
        public HttpResponseMessage GetUserInfoAll()
        {
            List<UserInfo> user = new List<UserInfo>(){new UserInfo (){ ID=1,UserName="znx",UserPass="test",Email="123123@163.com",RegTime=DateTime.Now},
                new UserInfo (){ ID = 2, UserName = "xmh", UserPass = "test", Email = "123123@163.com", RegTime = DateTime.Now } };
            return new HttpResponseMessage()
            {
                RequestMessage = Request,
                Content = new StringContent(SimpleXmlConvert.XmlSerialize<List<UserInfo>>(user))
            };
        }

返回结果如下在这里插入图片描述

SimpleXmlConvert类见下

序列Xml类

1.第一种序列化SimpleXmlConvert

public class SimpleXmlConvert
    {
        /// <summary>
        /// 将实体类型转换为XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize<T>(T obj)
        {
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    Type t = obj.GetType();
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(sw, obj);
                    sw.Close();

                    return sw.ToString();
                }
            }
            catch (Exception e)
            {

                throw new Exception("将实体类型对象转换成XML异常",e) ;
            }
        }

        public static T DESerializer<T>(string strXML) where T : class
        {
            try
            {
                using (StringReader rd=new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(rd) as T;
                }
            }
            catch (Exception e)
            {

                throw new Exception("将XML字符串转换成实体对象异常", e);
            }
        }
    }

2.第二种序列化方法

public class SimpleXmlConverter2
    {
        public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new()
        {
            if (entities == null || entities.Count == 0)
            {
                return string.Empty;
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLine(XmlResource.XmlHeader);

            XElement element = ToXElement<T>(entities, rootName);
            builder.Append(element.ToString());

            return builder.ToString();
        }

        public static XmlDocument ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new()
        {
            if (entities == null || entities.Count == 0)
            {
                return null;
            }

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(ToXml<T>(entities, rootName));

            return xmlDocument;
        }

        public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new()
        {
            if (entities == null || entities.Count == 0)
            {
                return null;
            }
          
            return  XDocument.Parse(ToXml<T>(entities, rootName));
        }

        public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new()
        {
            if (entities == null || entities.Count == 0)
            {
                return null;
            }
             
            if (string.IsNullOrWhiteSpace(rootName))
            {
                rootName = typeof(T).Name + XmlResource.XmlRootNameSuffix;
            }

            XElement element = new XElement(rootName);

            foreach (T entity in entities)
            {
                element.Add(ToXElement<T>(entity));
            }

            return element;
        }

        public static string ToXml<T>(T entity) where T : new()
        {
            if (entity == null)
            {
                return string.Empty;
            }

            XElement element = ToXElement<T>(entity);

            return element.ToString();
        }

        public static XElement ToXElement<T>(T entity) where T : new()
        {
            if (entity == null)
            {
                return null;
            }

            XElement element = new XElement(typeof(T).Name);
            PropertyInfo[] properties = typeof(T).GetProperties();
            XElement innerElement = null;
            object propertyValue = null;

            foreach (PropertyInfo property in properties)
            {
                propertyValue = property.GetValue(entity, null);
                innerElement = new XElement(property.Name, propertyValue);
                element.Add(innerElement);
            }

            return element;
        }

        public static XElement ToXElement(Type type) 
        {
            if (type == null)
            {
                return null;
            }

            XElement element = new XElement(type.Name);
            PropertyInfo[] properties = type.GetProperties();
            XElement innerElement = null;

            foreach (PropertyInfo property in properties)
            {
                innerElement = new XElement(property.Name, null);
                element.Add(innerElement);
            }

            return element;
        }
    }

WebApi路由配置

1.webapi路由在App_Start文件夹下WebApiConfig.cs
2.路由默认不更改情况下 自带的Get、Post,Put,Delete方法只可使用一次 可以在方法前添加标签[HttpGet]、[HttpPost]可使用多次
路由请求地址
https://localhost:44310/api/test/GetUserInfoAll

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页