实例介绍
【实例简介】
【实例截图】
【核心代码】
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Security.Cryptography.X509Certificates; namespace CallWcfRest { public class UserInfo { public string userName { get ; set ; } public string userPassword { get ; set ; } } class Program { static void Main( string [] args) { //客户端证书的处理 X509Certificate2 cert = GetX509Certificate(); string dataUrl = Properties.Settings.Default[ "DataUrl" ].ToString(); string loginUrl = Properties.Settings.Default[ "LoginUrl" ].ToString(); bool isAnoymous = true ; Console.WriteLine( "请输入用户名:" ); string user = Console.ReadLine(); Console.WriteLine( "请输入密码:" ); string pwd = Console.ReadLine(); UserInfo info = new UserInfo { userName = user, userPassword = pwd }; //先访问LoginService,得到授权 var request = (HttpWebRequest)WebRequest.Create(loginUrl); request.ContentType = "application/json;charset=utf-8" ; request.Method = "POST" ; request.KeepAlive = true ; //request.ClientCertificates.Add(cert); //使用JSON.NET将对象序列化成JSON字符串 var requestBody = JsonConvert.SerializeObject(info); byte [] databytes = Encoding.UTF8.GetBytes(requestBody); request.ContentLength = databytes.Length; using (var writer = request.GetRequestStream()) { writer.Write(databytes, 0, databytes.Length); } var response = request.GetResponse(); var encryptedCookie = response.Headers[ "Set-Cookie" ]; using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { if (reader.ReadToEnd() == "true" ) { Console.WriteLine( "登录成功" ); isAnoymous = false ; } } } //如果未能通过Forms身份验证 if (isAnoymous) { Console.WriteLine( "登录失败" ); return ; } //访问DataService var request1 = (HttpWebRequest)WebRequest.Create(dataUrl); request1.Method = "GET" ; request1.Headers[ "Cookie" ] = encryptedCookie; var response1 = request1.GetResponse(); using (var stream = response1.GetResponseStream()) { using (var reader = new StreamReader(stream)) { string res = reader.ReadToEnd(); //使用JSON.NET进行反序列化 var obj = JsonConvert.DeserializeObject<dynamic>(res); Console.WriteLine( "......你将得到数据....." ); Console.WriteLine(obj[1].StringValue); } } } private static X509Certificate2 GetX509Certificate() { X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyEggSoft" , false ); return certs[0]; } } } |
服务端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; using System.IO; using System.Web; namespace WcfRestService5 { [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class FileService { [WebGet(UriTemplate = "" )] public string ShowTest() { return "只是测试一下" ; } /// <summary> /// 显示图片 /// </summary> /// <param name="image">图片名</param> /// <returns>图片字节流</returns> [WebGet(UriTemplate = "Show/{image}" )] public Stream ShowImage( string image) { string folder = System.Web.Hosting.HostingEnvironment.MapPath( "~/images" ); WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg" ; var file = Path.Combine(folder, image); return File.OpenRead(file); } /// <summary> /// 下载文件,以HTTP响应方式写回 /// </summary> /// <param name="filename">文件名</param> [WebGet(UriTemplate = "DownLoad/{filename}" )] public void GetFile( string filename) { string folder = System.Web.Hosting.HostingEnvironment.MapPath( "~/files" ); var FullName = Path.Combine(folder, filename); if (File.Exists(FullName)) { FileInfo DownLoadFile = new FileInfo(FullName); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = false ; HttpContext.Current.Response.ContentType = "application/octer-stream" ; HttpContext.Current.Response.AppendHeader( "Content-Disposition" , "attachment:filename=" HttpUtility.UrlEncode(DownLoadFile.FullName, System.Text.Encoding.UTF8)); HttpContext.Current.Response.AppendHeader( "Content-Length" , DownLoadFile.Length.ToString()); HttpContext.Current.Response.WriteFile(DownLoadFile.FullName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } } /// <summary> /// 上传文件,这个地方用form表单提交文件测试是成功了的,file是要保存的文件名 /// </summary> /// <param name="stream">上传文件字节流</param> /// <param name="file">要保存的文件名</param> /// <returns></returns> [WebInvoke(UriTemplate = "Add/{file}" , Method = "POST" )] public bool AddFile(Stream stream, string file) { if (! string .IsNullOrEmpty(file)) { string folder = System.Web.Hosting.HostingEnvironment.MapPath( "~/Files" ); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string path = Path.Combine(folder, file); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) { long ByteLength = WebOperationContext.Current.IncomingRequest.ContentLength; byte [] fileContent = new byte [ByteLength]; stream.Read(fileContent, 0, fileContent.Length); fs.Write(fileContent, 0, fileContent.Length); fs.Flush(); return true ; } } return false ; } } } |
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论