Advertisement
Serginio

Untitled

Mar 9th, 2016
5,488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Web;
  10. using System.IO;
  11. using System.Threading.Tasks;
  12. namespace WebTestHttpClient.Controllers
  13. {
  14.     public class ValuesController : ApiController
  15.     {
  16.         // GET api/values
  17.         public IEnumerable<string> Get()
  18.         {
  19.             return new string[] { "value1", "value2" };
  20.         }
  21.  
  22.         private string ПолучитьЗначения(IEnumerable<string> values)
  23.         {
  24.             var sb = new StringBuilder();
  25.  
  26.             foreach (var h in values)
  27.             {
  28.                 sb.Append(h+",");
  29.  
  30.             }
  31.  
  32.             if (sb.Length == 0) return "";
  33.  
  34.             return sb.ToString(0, sb.Length - 1);
  35.         }
  36.  
  37.         [HttpGet]
  38.         public async Task<string> GetId()
  39.         {
  40.             await Task.Delay(1000);
  41.            
  42.             return "1";
  43.  
  44.  
  45.         }
  46.  
  47.         [HttpGet]
  48.         public async Task<string> GetIdAsync(string id)
  49.         {
  50.             await Task.Delay(1000);
  51.             return id;
  52.  
  53.  
  54.         }
  55.  
  56.         void ЗаполнитьКукиИХэдеры(StringBuilder sb)
  57.         {
  58.             sb.AppendLine("======= Куки ");
  59.          
  60.             foreach (var cookies in Request.Headers.GetCookies())
  61.             {
  62.                 foreach (var cooki in cookies.Cookies)
  63.                sb.AppendLine(cooki.Name + ":" + cooki.Value);
  64.  
  65.             }
  66.  
  67.  
  68.  
  69.                 sb.AppendLine("======= Заголовки ");
  70.             foreach (var h in Request.Headers)
  71.             {
  72.                 sb.AppendLine(h.Key + ":" + ПолучитьЗначения(h.Value));
  73.  
  74.             }
  75.         }
  76.         // GET api/values/5
  77.         [HttpGet]
  78.         public HttpResponseMessage GetHeaders()
  79.         {
  80.             var cookie = new CookieHeaderValue("id", "12345"); // имя куки - id, значение - 12345
  81.             cookie.Expires = DateTimeOffset.Now.AddDays(1); // время действия куки - 1 день
  82.             cookie.Domain = Request.RequestUri.Host; // домен куки
  83.             cookie.Path = "/"; // путь куки
  84.  
  85.             var sb = new StringBuilder();
  86.  
  87.             ЗаполнитьКукиИХэдеры(sb);
  88.  
  89.             var response = Request.CreateResponse<string>(HttpStatusCode.OK, sb.ToString());
  90.             response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
  91.             return response;
  92.  
  93.         }
  94.  
  95.         // POST api/values
  96.         [HttpPost]
  97.         public string SendStr([FromBody]string value)
  98.         {
  99.             string Id = "";
  100.  
  101.             CookieHeaderValue cookie = Request.Headers.GetCookies("id").FirstOrDefault();
  102.             if (cookie != null)
  103.             {
  104.                 Id = cookie["id"].Value;
  105.             }
  106.  
  107.             var sb = new StringBuilder();
  108.  
  109.             sb.AppendLine("value=" + value);
  110.             sb.AppendLine("id=" + Id);
  111.  
  112.             ЗаполнитьКукиИХэдеры(sb);
  113.  
  114.             return sb.ToString();
  115.  
  116.         }
  117.  
  118.         [HttpPost]
  119.         public string SendStr2()
  120.         {
  121.             string Id = "";
  122.  
  123.             CookieHeaderValue cookie = Request.Headers.GetCookies("id").FirstOrDefault();
  124.             if (cookie != null)
  125.             {
  126.                 Id = cookie["id"].Value;
  127.             }
  128.  
  129.             var sb = new StringBuilder();
  130.  
  131.             string value = Request.Content.ReadAsStringAsync().Result;
  132.             sb.AppendLine("value=" + value);
  133.             sb.AppendLine("id=" + Id);
  134.  
  135.             ЗаполнитьКукиИХэдеры(sb);
  136.  
  137.             return sb.ToString();
  138.  
  139.         }
  140.  
  141.         [HttpPost]
  142.         public string SendStream()
  143.         {
  144.             string Id = "";
  145.  
  146.             CookieHeaderValue cookie = Request.Headers.GetCookies("id").FirstOrDefault();
  147.             if (cookie != null)
  148.             {
  149.                 Id = cookie["id"].Value;
  150.             }
  151.  
  152.             var sb = new StringBuilder();
  153.  
  154.             string value = Request.Content.ReadAsStringAsync().Result;
  155.             sb.AppendLine("value=" + value);
  156.             sb.AppendLine("id=" + Id);
  157.  
  158.             foreach (var h in Request.Headers)
  159.             {
  160.                 sb.AppendLine(h.Key + ":" + ПолучитьЗначения(h.Value));
  161.  
  162.             }
  163.  
  164.             return sb.ToString();
  165.  
  166.         }
  167.  
  168.  
  169.         [NonAction]
  170.         string fileName(MultipartFileData fileData)
  171.         {
  172.             string fileName = fileData.Headers.ContentDisposition.FileName;
  173.  
  174.             if (string.IsNullOrEmpty(fileName))
  175.             {
  176.                 return "";
  177.             }
  178.            
  179.             if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
  180.             {
  181.                 fileName = fileName.Trim('"');
  182.             }
  183.             if (fileName.Contains(@"/") || fileName.Contains(@"\"))
  184.             {
  185.                 fileName = Path.GetFileName(fileName);
  186.             }
  187.  
  188.             return fileName;
  189.         }
  190.         [HttpPost]
  191.         public async Task<HttpResponseMessage> SendFiles()
  192.         {
  193.             if (!Request.Content.IsMimeMultipartContent())
  194.             {
  195.                 throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
  196.             }
  197.  
  198.             string root = HttpContext.Current.Server.MapPath("~/App_Data");
  199.             var provider = new MultipartFormDataStreamProvider(root);
  200.  
  201.             try
  202.             {
  203.                 StringBuilder sb = new StringBuilder(); // Holds the response body
  204.  
  205.                 // Read the form data and return an async task.
  206.                 await Request.Content.ReadAsMultipartAsync(provider);
  207.  
  208.                 // This illustrates how to get the form data.
  209.                 foreach (var key in provider.FormData.AllKeys)
  210.                 {
  211.                     foreach (var val in provider.FormData.GetValues(key))
  212.                     {
  213.                         sb.Append(string.Format("{0}: {1}\n", key, val));
  214.                     }
  215.                 }
  216.  
  217.                 // This illustrates how to get the file names for uploaded files.
  218.                 foreach (var file in provider.FileData)
  219.                 {
  220.                     var fileInfo = new FileInfo(file.LocalFileName);
  221.                     sb.Append(string.Format("Uploaded file: {0} {1} ({2} bytes)\n", fileName(file), fileInfo.Name, fileInfo.Length));
  222.                 }
  223.                 return new HttpResponseMessage()
  224.                 {
  225.                     Content = new StringContent(sb.ToString())
  226.                 };
  227.             }
  228.             catch (System.Exception e)
  229.             {
  230.                 return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
  231.             }
  232.  
  233.  
  234.         }
  235.  
  236.         [HttpPost]
  237.         public string SendUserPassword(WebTestHttpClient.Areas.HelpPage.Models.UserPassword UP)
  238.         {
  239.  
  240.             if (UP == null) return "null";
  241.             return UP.Login+":"+UP.Password;
  242.  
  243.         }
  244.         // PUT api/values/5
  245.         public void Put(int id, [FromBody]string value)
  246.         {
  247.         }
  248.  
  249.         // DELETE api/values/5
  250.         public void Delete(int id)
  251.         {
  252.         }
  253.     }
  254. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement