C# 实现RestFul 服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace RestfulService
{
    // 定义两种方法,1、GetInputFunc:input,返回input;2、PostInputFunc:通过POST请求,传入input,返回input
    [ServiceContract(Name = "GetInputService")]
    public interface IRestFulDemoServices
    {
        //说明:GET请求
        //WebGet默认请求是GET方式
        //UriTemplate(URL Routing)input必须要方法的参数名必须一致不区分大小写)
        [OperationContract]
        [WebGet(UriTemplate = "GetInput/{input}", BodyStyle = WebMessageBodyStyle.Bare)]
        string GetInputFunc(string input);

        //说明:POST请求
        //WebInvoke请求方式有POST、PUT、DELETE等,所以需要明确指定Method是哪种请求的,这里我们设置POST请求。
        //UriTemplate(URL Routing)input必须要方法的参数名必须一致不区分大小写)
        //RequestFormat规定客户端必须是什么数据格式请求的(JSon或者XML),不设置默认为XML
        // ResponseFormat规定服务端返回给客户端是以是什么数据格返回的(JSon或者XML)
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "GetInput/{input}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string PostInputFunc(string input);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestFulDemoServices : IRestFulDemoServices
    {
        public string GetInputFunc(string Input)
        {
            return Input;
        }
        public string PostInputFunc(string Input)
        {
            return Input;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RestFulDemoServices demoServices = new RestFulDemoServices();
                WebServiceHost _serviceHost = new WebServiceHost(demoServices, new Uri("http://localhost:8000/"));
                _serviceHost.Open();
                Console.WriteLine("Web服务已开启...");
                Console.WriteLine("输入任意键关闭程序!");
                Console.ReadKey();
                _serviceHost.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Web服务开启失败:{0}\r\n{1}", ex.Message, ex.StackTrace);
            }
        }
    }
}

代码下载地址:https://download.csdn.net/download/u014378771/11430827

步骤:

一、新建解决方案。

二、添加新建项目

三、添加引用

 

四、复制代码即可实现C#服务。

五、测试

利用Postman测试结果如下。(虽然调用时URL一样,但是方法不一样,返回值不一样)

测试GET方法:注意左边的GET。

 

测试POST方法:注意左边的POST

 

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
C#实现RESTful API的方式上传文件,可以使用HttpClient类来发送请求。下面是一个示例代码: ```csharp string url = "http://example.com/api/upload"; string filePath = "C:\\example\\file.jpg"; using (var httpClient = new HttpClient()) { using (var form = new MultipartFormDataContent()) { using (var fileStream = new FileStream(filePath, FileMode.Open)) { using (var streamContent = new StreamContent(fileStream)) { form.Add(streamContent, "file", Path.GetFileName(filePath)); var response = await httpClient.PostAsync(url, form); if (response.IsSuccessStatusCode) { // 文件上传成功 } else { // 文件上传失败 } } } } } ``` 在上面的示例中,我们使用HttpClient类来发送POST请求,请求的URL是"http://example.com/api/upload"。我们创建了一个MultipartFormDataContent对象,用于包含上传的文件。使用FileStream类打开文件,然后使用StreamContent类将文件内容添加到MultipartFormDataContent对象中。最后,我们使用HttpClient类的PostAsync方法将请求发送到服务器,并等待响应。 注意,这里的文件名是通过Path.GetFileName方法获取的,因此需要确保文件路径中包含文件名。如果你想要自定义文件名,可以将第三个参数传递给StreamContent构造函数。 另外,如果需要在请求头中添加自定义的标头,可以使用HttpClient的DefaultRequestHeaders属性。例如: ```csharp httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer my_token"); ``` 这将在请求头中添加一个名为"Authorization"的标头,值为"Bearer my_token"。

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值