记录一个WEBAPI做的接口,上传下载文件,接受JSON数据返回JSON

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;   

 public class TaskFromMESController : ApiController
    {
        private const string _path = @"D:\ERP\222\";

        private string GetFile(string requestFileName, string UserId)
        {
            string rtnbyte = "";
            try
            {
                if (System.IO.File.Exists(_path + requestFileName))
                {
                    rtnbyte =getBinaryFile(_path + requestFileName).ToString();

                    return "{'Message':'" + rtnbyte + "','Success':1}";
                }
                else
                    return "{'Message':'未找到对应文件!','Success':0}";
            }
            catch (Exception ee)
            {
                return "{'Message':'" + ee.Message + "','Success':0}";
            }
            //return getBinaryFile(_path + requestFileName);
        }

        /// <summary>
        /// getBinaryFile:返回所给文件路径的字节数组。
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public byte[] getBinaryFile(string filename)
        {
            if (File.Exists(filename))
            {
                try
                {
                    ///打开现有文件以进行读取。
                    FileStream s = File.OpenRead(filename);
                    return ConvertStreamToByteBuffer(s);
                }
                catch
                {
                    return new byte[0];
                }
            }
            else
            {
                return new byte[0];
            }
        }
        /// <summary>
        /// ConvertStreamToByteBuffer:把给定的文件流转换为二进制字节数组。
        /// </summary>
        /// <param name="theStream"></param>
        /// <returns></returns>
        private byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
        {
            int b1;
            System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
            while ((b1 = theStream.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)b1));
            }
            theStream.Close();
            return tempStream.ToArray();
        }

        private string Delete(string fileName)
        {
            try
            {
                if (System.IO.File.Exists(_path + fileName))
                {

                    File.Delete(_path + fileName);

                    return "{'Message':'删除成功!','Success':1}";
                }
                else
                    return "{'Message':'未找到对应删除文件!','Success':0}";
            }
            catch (Exception ee)
            {
                return "{'Message':'" + ee.Message + "','Success':0}";
            }
        }

        private string Upload(string fileName, byte[] b)
        {
            try
            {
                File.WriteAllBytes(_path + fileName, b);
                if (System.IO.File.Exists(_path + fileName))
                    return "{'Message':'上传成功!','Success':1}";
                else
                    return "{'Message':'上传失败!','Success':0}";
            }
            catch (Exception ee)
            {
                return "{'Message':'" + ee.Message + "','Success':0}";
            }
        }

        [HttpGet]
        public string HelloWorld()
        {
            return "Hello  World !";
        }

        [HttpPost]
        public string GetUser(string name,string pwd)
        {
            return "[{'name':'" + name + "','pwd':'" + pwd + "'}]";
        }
        [HttpPost]
        public string TaskOpr(string JsonString)
        {
            try
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(JsonString);
                string rtnString = "{'Message':'','Success':0}";
                string RequestName = jo["RequestName"].ToString();
                string JsonData = jo["JsonData"].ToString();
                if (RequestName == "DeleteTask")
                    rtnString = DeleteTask(JsonData, jo["UserId"].ToString());
                else if (RequestName == "InsertTask")
                    rtnString = InsertTask(JsonData, jo["UserId"].ToString());
                else if (RequestName == "GetFile")
                    rtnString = GetFile(JsonData, jo["UserId"].ToString());
                else
                    rtnString = "{'Message':'未定义','Success':0}";
                return rtnString;
            }
            catch (Exception ee)
            {
                return "{'Message':'" + ee.Message + "','Success':0}";
            }


            //{"UserId": "129","Token": "Token","RequestName": "InsertTask","JsonData": "[{ 'TaskNumber':'20200102312', 'plan_order_no':'201905000007614','BatchNo':'123','PartSerialNo':'123tWEB333','ModuleNo':'123'}, {'TaskNumber':'20200102322',  'plan_order_no':'201905000007614','BatchNo':'123','PartSerialNo':'123tWEB334','ModuleNo':'1232'}]"}
        }

        //[WebMethod(Description = "删除任务工单")]
        private string DeleteTask(string JsonString, string userId)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("TaskNumber");
                dt.Columns.Add("PartSerialNo");
                //string JArrays = @"[{ 'TaskNumber':'1'},{'TaskNumber':'2'}]";
                //JsonString = JArrays;
                JArray jarray = (JArray)JsonConvert.DeserializeObject(JsonString);
                string ColumnName = "";
                int e = 0;
                for (int i = 0; i < jarray.Count; i++)
                {
                    DataRow newRow = dt.NewRow();
                    if (jarray[i][ColumnName] == null || jarray[i][ColumnName].ToString() == "")
                        throw new Exception(ColumnName + "字段值不能为空!");
                    newRow[ColumnName] = jarray[i][ColumnName].ToString();
                    newRow.EndEdit();
                    e = 2;
                    dt.Rows.Add(newRow);
                }
                (new InsertTask()).DeleteTask(dt);
                return "{'Message':'删除成功!','Success':1}";
            }
            catch (Exception ee)
            {
                return "{'Message':'" + ee.Message + "','Success':0}";
            }
        }


        //[WebMethod(Description = "插入任务工单")]
        private string InsertTask(string JsonString, string userId)
        {
            //return "{'Message':'调用成功!','Success':1}";
            //{'order_no':'2020010230', 'plan_order_no':'202000629','c_code':'2020095'}
            //JObject jo = (JObject)JsonConvert.DeserializeObject(JsonString);
            //        string JArrays = @"[{ 'TaskNumber':'20200102312', 'plan_order_no':'202005000007609','BatchNo':'1','PartSerialNo':'12WEB333','ModuleNo':'23','CreateUser':'2239'},
            //                        {'TaskNumber':'20200102322',  'plan_order_no':'202005000007609','BatchNo':'32','PartSerialNo':'WEB334','ModuleNo':'232','CreateUser':'123'}]";
            //JsonString = JArrays;
            int e = 0;
            string error = "";
            try
            {
                string ColumnName = "";
                DataTable dt = new DataTable();
                JArray jarray = (JArray)JsonConvert.DeserializeObject(JsonString);
                dt.Columns.Add("TaskNumber");
                dt.Columns.Add("plan_order_no");
                dt.Columns.Add("BatchNo");
                dt.Columns.Add("PartSerialNo");
                dt.Columns.Add("ModuleNo");
                e = 1;
                for (int i = 0; i < jarray.Count; i++)
                {
                    ColumnName = "";
                    DataRow newRow = dt.NewRow();
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ColumnName = dt.Columns[j].ColumnName.ToString();
                        if (jarray[i][ColumnName] == null || jarray[i][ColumnName].ToString() == "")
                            throw new Exception(ColumnName + "字段值不能为空!");
                        newRow[ColumnName] = jarray[i][ColumnName].ToString();
                    }
                    newRow.EndEdit();
                    e = 2;
                    dt.Rows.Add(newRow);
                }
                e = 3;
                (new InsertTask()).Update(dt);
                string Message = "保存成功" + jarray.Count + "条数据";
                return "{'Message':'" + Message + "','Success':1}";
            }
            catch (Exception ee)
            {
                if (e == 1)
                    error = "JSON字符串缺少数据项或者关键字名称不一致:" + ee.Message;
                else if (e == 2)
                    error = "传入JSON串与接口个数不一致:" + ee.Message;
                else if (e == 3)
                    error = "插入数据库有误:" + ee.Message;
                else
                    error = ee.Message;
                return "{'Message':'" + error + "','Success':0}";
            }
        }
    }

项目需要MVC4 ,.netFramework 4.0 ,VS2010,新建WEBAPI模板,放入这个到控制器即可

有项目源码,如有需要下方留言,无偿赠送

  • 1
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 4

打赏作者

金大哈

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值