首页 > 编程语言 >C# 调用 MVC Controller 方法, 传递图片

C# 调用 MVC Controller 方法, 传递图片

时间:2022-11-22 13:57:40浏览次数:40  
标签:string get C# System Controller MVC IO using public

1.C# 调用  MVC Controller 的方法,文字,图片当参数。

2.http方法的参数只能是字符串,图片以byte[]二进制 传递。

3.Newtonsoft.Json.JsonConvert.SerializeObject   会自动将byte[] 转为 base64(网络编码格式)的字符串。

------------------------------------------------------- A服务端

public string SetMouseAlarm(string dbname, string pid, string remarks, byte[] ImgBytes)
        {
            try
            {
                string sql = "INSERT INTO dbo.T_AlarmInfo VALUES(" + pid + ", NULL, NULL, NULL, '老鼠', 1, NULL, 0, 1, '一般', GETDATE(), '', NULL, 0, '" + remarks + "');SELECT MAX(ID) FROM dbo.T_AlarmInfo;";
                string id = DBHelper.ExecuteNonQurey1(dbname, sql, CommandType.Text, null).ToString();
                ////////////////
                System.IO.MemoryStream ms = new System.IO.MemoryStream(ImgBytes);
                System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                string imagePath = Server.MapPath("~/ShangChuan/LaoShuImages");
                //保存到磁盘文件
                if (!System.IO.Directory.Exists(imagePath))
                    System.IO.Directory.CreateDirectory(imagePath);
                //img.Save(System.IO.Path.Combine(imagePath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                img.Save(System.IO.Path.Combine(imagePath, id + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

                ms.Dispose();
                return "1";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
View Code

 

 

B---------------客户端调用

1.客户端http封装类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace WebApplication1.HelpClass
{
    public class HttpClient
    {
        /// <summary>
        /// Seivice URL
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 内容,body,fields参数
        /// </summary>
        public string Data { get; set; }
        /// <summary>
        /// Cookie,保证登录后,所有访问持有一个Cookie;
        /// </summary>
        static CookieContainer Cookie = new CookieContainer();
        /// <summary>
        /// Seivice Method ,post,get,delete,put,等等,支持大小写
        /// </summary>
        public string Method { get; set; }

        /// <summary>
        /// HTTP访问
        /// </summary>
        public string AsyncRequest()
        {
            HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
            httpRequest.Method = Method;
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min

            using (Stream reqStream = httpRequest.GetRequestStream())
            {
                var bytes = UnicodeEncoding.UTF8.GetBytes(Data);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            using (var repStream = httpRequest.GetResponse().GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }

        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                return responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }
    }

    public class UserInfo
    {
        public string dbname { get; set; }
        public string pid { get; set; }
        public string remarks { get; set; }
        public byte[] ImgBytes { get; set; }

    }

}
View Code

2.调用方法

public void aaaa()
        {
            HelpClass.HttpClient httpClient = new HelpClass.HttpClient();
            httpClient.Url = "http://172.16.6.133:8067/Alarm/SetMouseAlarm";
            httpClient.Method = "post";

            HelpClass.UserInfo userInfo = new HelpClass.UserInfo();
            userInfo.dbname = "DB_YWSystem_cqly5";
            userInfo.pid = "1";
            userInfo.remarks = "老鼠报警3";
            userInfo.ImgBytes = GetPictureData();

            httpClient.Data = Newtonsoft.Json.JsonConvert.SerializeObject(userInfo);
            var iResult = httpClient.AsyncRequest();
            //var iResult = Newtonsoft.Json.Linq.JObject.Parse();
        }



        //图片转成二进制
        public byte[] GetPictureData()
        {
            string path = Server.MapPath("~/ShangChuan/LaoShuImages/AA.jpg");
            System.IO.FileStream a = new System.IO.FileStream(path, System.IO.FileMode.Open);
            byte[] byData = new byte[a.Length];
            a.Read(byData, 0, byData.Length);
            a.Close();
            return byData;
            //SetMouseAlarm("DB_YWSystem_cqly5", "1", "发现老鼠报警...", byData);http://172.16.6.133:8067/Alarm/SetMouseAlarm
        }
View Code

 

标签:string,get,C#,System,Controller,MVC,IO,using,public
From: https://www.cnblogs.com/Evan-Pei/p/16914883.html

相关文章

  • asp.net中ScriptManager是做什么用的
    https://zhidao.baidu.com/question/477322362.html命名空间:System.Web.UI程序集:System.Web.Extensions.dll功能跟Page上的ClientScript差不多,不过主要是用来支持ASP.N......
  • 对比Jmeter和Locust,阿里性能专家全方位分析
    在实际性能测试过程中,到底选择Jmeter还是Locust,除了语言上的差异,它们各自有什么优点和缺点吗?从不同的维度,对这两款工具来做下对比分析,希望能帮助大家选择适合自己的工具。......
  • LAB-13:创建PVC
    LAB-13:创建PVCLAB概述创建一个名字为pv-volume的pvc,指定storageClass为csi-hostpath-sc,大小为10Mi。然后创建一个Pod,名字为web-server,镜像为nginx,并且挂载该P......
  • window对象和document对象
    window对象1.对象属性1.窗口自身2.window.self引用本窗口3.window.name窗口命名4.window.defaultStatus设定窗口状态栏信息5.window.locationURL地址,配......
  • mac mini 设置显示器刷新频率黑屏后如何复原。
    昨天晚上手贱,改了下macmini连接显示器的刷新频率从60HZ改成30HZ,改完之后黑屏了,显示器只显示这个:不能显示此视频模式请将电脑重新玻置为1920×1080@60Hz如下图 这怎么......
  • MBR16200FCT-ASEMI塑封肖特基二极管MBR16200FCT
    编辑:llMBR16200FCT-ASEMI塑封肖特基二极管MBR16200FCT型号:MBR16200FCT品牌:ASEMI封装:ITO-220AB正向电流:16A反向电压:200V引线数量:3芯片个数:2芯片尺寸:102MIL漏电流:1......
  • C/C++预处理命令
    防止重复包含头文件#ifndef__文件名大写_H__#define__文件名大写_H__#endif//__文件名大写_H__//c++pragmaonce较老编译器不支持,以上两种方法都行。......
  • etcd备份
    etcd是kubernetes集群极为重要的一块服务,存储了kubernetes集群所有的数据信息,如Namespace、Pod、Service、路由等状态信息。如果etcd集群发生灾难或者etcd集群数据丢失,都......
  • 【转】C#-INotifyPropertyChanged(解决数据绑定的界面刷新问题)
    C#-INotifyPropertyChanged(解决数据绑定的界面刷新问题) 最近做项目用到DataGridView,用它绑定数据源后,如果数据源中的数据修改无法及时刷新到控件上,必须切换单元......
  • oracle查看执行计划
    1.在执行查询的sql前加上 explainplanFOR例如:explainplanFORselectsysdatefromdual;2.查看生成的执行计划selectplan_table_outputfromTABLE(DBMS_XPLAN.DI......