C# WebApi

  1. 创建WebApi项目

C# WebApi_第1张图片

  1. Web API 配置和服务

    App_start ——> WebApiConfig.cs

  config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "service/{controller}/{action}/{id}",
               defaults: new {
      id = RouteParameter.Optional }
           );
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            
  1. 封装公用方法

    Models——>Helper
    HttpHelper.cs

   public class HttpHelper
    {
     
        public static HttpResponseMessage StringNoAes(string str)
        {
     
            return new HttpResponseMessage {
      Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "text/plain") };
        }
    }
Models——>Respon
	responseApi.cs  返回格式json
	 public class ResponseApi
    {
     
        /// 
        /// 数据
        /// 
        public object data {
      get; set; }
        /// 
        /// 获取成功
        /// 
        public bool success {
      get; set; }
        /// 
        /// 正确信息
        /// 
        public string msg {
      get; set; }
    }
Models——>Mode
	GetPost.cs   //Get Post 接收数据
	OnLineClass.cs //用于接收数据 json解析
public class GetPost
    {
     
        public static string GetHttpRequestData()
        {
     
            var data = "";
            switch (HttpContext.Current.Request.HttpMethod)
            {
     
                case "POST":
                    data = HttpUtility.UrlDecode(Convert.ToString(HttpContext.Current.Request.Form["data"]));
                    break;
                case "GET":
                    data = HttpUtility.UrlDecode(Convert.ToString(HttpContext.Current.Request.QueryString["data"]));
                    break;
            }
            return data;
        }
 public class OnLineClass
    {
     
        public string merid {
      get; set; }

        public string name {
      get; set; }

        public MqueryMemberfields fields {
      get; set; } = new MqueryMemberfields();
    }


    public class MqueryMemberfields
    {
     
        /// 
        /// 卡的状态
        /// 
        public string cardStatus {
      get; set; }
    }
  1. 控制器 Controllers
    Controllers——>UserInfoController.cs
 public class UserInfoController : ApiController
    {
     
        /// 
        /// 测试接口
        /// 
        /// 
        [HttpGet,HttpPost]
        public HttpResponseMessage ApiCs()
        {
     
            var data = GetPost.GetHttpRequestData();
            Log4Helper.YLLog("data=>" + data);
            ResponseApi responseApi = new ResponseApi();
            
            OnLineClass onlin = null;
            try
            {
     
                onlin = JsonConvert.DeserializeObject(data, typeof(OnLineClass)) as OnLineClass;
                if (!string.IsNullOrEmpty(onlin.merid))
                {
     
                    //JObject array = new JObject();
                    //array.Add("merid", onlin.merid.ToString());
                    //array.Add("name", onlin.name.ToString());
                    //responseApi.msg = "成功";
                    //responseApi.success = true;
                    //responseApi.data = array;

                    OnLineClass onLine = new OnLineClass();
                    onLine.merid = onlin.merid.ToString();
                    onLine.name = onlin.name.ToString();
                    onLine.fields.cardStatus = "0";
                    responseApi.msg = "成功";
                    responseApi.success = true;
                    responseApi.data = onLine;


                }
                else 
                {
     
                    responseApi.msg = "商户不存在";
                    responseApi.success = false;
                }
               
            }
            catch (Exception ex) 
            {
     
                responseApi.msg = "err:" + ex.Message;
                responseApi.success = false;
            }

            var content = JsonConvert.SerializeObject(responseApi);            
            return HttpHelper.StringNoAes(content);
            
        }

启用访问地: https://localhost:44322/service/userinfo/apics

返回结果:

{
“data”: {
“merid”: “123456”,
“name”: “123”,
“fields”: {
“cardStatus”: “0”
}
},
“success”: true,
“msg”: “成功”
}

你可能感兴趣的:(C#,WebApi)