WebAPI的简单使用及文件传递

首先NuGet下载安装ASP.NET Web API Self Host程序包;

 

创建服务端

创建接口类:

1 public class ExcuteController : ApiController

编写接口函数:

复制代码
 1         /// <summary>
 2         /// 接口连接测试
 3         /// </summary>
 4         /// <param name="name"></param>
 5         /// <returns></returns>
 6         [HttpPost]
 7         public HttpResponseMessage Ping([FromUri] string name)
 8         {
 9             Console.WriteLine("RCV:" + name);
10             return Request.CreateResponse(HttpStatusCode.OK, "OK");
11         }
Ping
复制代码

上传文件函数:

复制代码
 1         /// <summary>
 2         /// 上传文件
 3         /// </summary>
 4         /// <param name="path"></param>
 5         /// <returns></returns>
 6         [HttpPost]
 7         public async Task<HttpResponseMessage> Uploading([FromUri] string path)
 8         {
 9             try
10             {
11                 if (!Directory.Exists(path))
12                     Directory.CreateDirectory(path);
13                 var provider = new MultipartFormDataStreamProvider(path);
14                 await Request.Content.ReadAsMultipartAsync(provider);
15                 foreach (var file in provider.FileData)
16                 {
17                     var header = file.Headers.ContentDisposition;
18                     var name = header.FileNameStar ?? header.FileName;
19                     var currentName = file.LocalFileName;
20                     var filePath = path + name;
21                     File.Move(currentName, filePath);
22                     Console.WriteLine("RCV:" + filePath);
23                     using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
24                     {
25                         using (StreamReader sr = new StreamReader(fs))
26                         {
27                             while (true)
28                             {
29                                 string str = sr.ReadLine();
30                                 if (string.IsNullOrEmpty(str))
31                                     break;
32                                 Console.WriteLine(str);
33                             }
34                         }
35                     }
36                 }
37                 return Request.CreateResponse(HttpStatusCode.OK, "OK");
38             }
39             catch (Exception ex)
40             {
41                 return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
42             }
43         }
Uploading
复制代码

开启API服务:

复制代码
 1     public class WebAPIClass
 2     {
 3         private static HttpSelfHostServer server = null;
 4         public static void Start()
 5         {
 6             try
 7             {
 8                 Uri address = new Uri("http://127.0.0.1:60055/");
 9                 HttpSelfHostConfiguration con = new HttpSelfHostConfiguration(address);
10                 con.Routes.MapHttpRoute(
11                     name: "DefaultApi",
12                     routeTemplate: "{controller}/{action}/{id}",
13                     defaults: new { id = RouteParameter.Optional });
14                 con.MaxReceivedMessageSize = int.MaxValue;
15 
16                 server = new HttpSelfHostServer(con);
17                 server.OpenAsync().Wait();
18             }
19             catch (Exception ex)
20             { }
21             Console.WriteLine("WebAPI Start");
22         }
23     }
Server Start
复制代码

 

实现客户端调用

1 static HttpClient client = new HttpClient();

调用Ping函数:

复制代码
1         private static async Task<string> api_Ping()
2         {
3             string address = "http://127.0.0.1:60055/Excute/";
4             address += "Ping?name=Test";
5             HttpContent content = new StringContent("");
6             HttpResponseMessage response = client.PostAsync(address, content).Result;
7             string res = await response.Content.ReadAsStringAsync();
8             return res;
9         }
Ping
复制代码

调用Uploading函数:

复制代码
 1         private static async Task<string> api_Send()
 2         {
 3             string file = "D:\\123.txt";
 4             Console.WriteLine("SendFile:" + file);
 5             string address = "http://127.0.0.1:60055/Excute/";
 6             address += "Uploading?path=D:\\";
 7             var content = new MultipartFormDataContent();
 8             var fscon = new StreamContent(File.OpenRead(file));
 9             fscon.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
10             content.Add(fscon, "file", "456.txt");
11             HttpResponseMessage response = client.PostAsync(address, content).Result;
12             string res = await response.Content.ReadAsStringAsync();
13             return res;
14         }
Uploading
复制代码

 

1.多参数:para1=val1&para2=val2...

2.把上传文件调过来就实现下载文件.

posted @   [春风十里]  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示