侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

C#控制台程序如何创建HTTP Rest API

码峰
2022-10-08 / 0 评论 / 0 点赞 / 1,814 阅读 / 1,262 字 / 正在检测是否收录...
广告 广告

前言

本文是关于如何创建Rest API C#控制台应用程序的,在此之前,我们必须知道什么是RESTful api。RESTful API是一种应用程序接口(API),它使用HTTP方法请求GET、PUT、POST和DELETE数据。
RESTful API(也称为RESTfulWeb服务)基于表示状态传输(REST)技术,这是web服务开发中常用的一种体系结构风格和通信方法。
REST技术通常是更健壮的简单对象访问协议(SOAP)技术的首选,因为REST利用的带宽更少,更适合互联网使用。网站的API是允许两个软件程序相互通信的代码。API规定了开发人员编写程序从操作系统或其他应用程序请求服务的正确方式。
浏览器通常使用的REST可以看作是互联网的语言。随着云使用的增加,API正在出现以公开web服务。REST是构建允许用户连接云服务并与云服务交互的API的合理选择。RESTful API被亚马逊、谷歌、LinkedIn和Twitter等网站使用。
在本指南中,我将告诉您如何制作Rest API C#控制台应用程序,从在Microsoft Visual Studio中制作项目开始,直到在浏览器中进行测试。您也可以使用计算机直接遵循此说明。

操作步骤

创建控制台项目

使用Microsoft Visual Studio 2015等创建新的控制台项目应用程序(示例:restservice)
如下图:
image-1665296621662

编辑app.config

参考内容如下:

<?xml version="1.0" encoding="utf-8"?>      
<configuration>      
      
  <startup>      
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />      
  </startup>      
      
  <system.serviceModel>      
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>      
      
    <bindings>      
      <!--<wsHttpBinding>-->      
      <basicHttpBinding>      
        <binding name="basicHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">      
          <security mode="None">      
            <!--<transport clientCredentialType="None" />-->      
          </security>      
          <!--<reliableSession enabled="true" />-->      
        </binding>      
      </basicHttpBinding>      
      <!--</wsHttpBinding>-->      
      
      <webHttpBinding>      
        <binding name="webHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">      
          <security mode="None">      
            <!--<transport clientCredentialType="None" />-->      
          </security>      
        </binding>      
      </webHttpBinding>      
    </bindings>      
      
    <services>      
      
      <service name="restservice.Service">      
        <endpoint address ="rest" binding="webHttpBinding" bindingConfiguration="webHttp" contract="restservice.IService" behaviorConfiguration="web"></endpoint>      
        <host>      
          <baseAddresses>      
            <add baseAddress="http://localhost:8080" />      
          </baseAddresses>      
        </host>      
      </service>      
    </services>      
      
    <behaviors>      
      <serviceBehaviors>      
        <behavior name="mexBehaviour">      
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />      
          <!-- rest api-->      
          <serviceDebug includeExceptionDetailInFaults="false"/>      
        </behavior>      
      </serviceBehaviors>      
      
      <endpointBehaviors>      
        <behavior name="web">      
          <webHttp/>      
        </behavior>      
      </endpointBehaviors>      
    </behaviors>      
  </system.serviceModel>      
      
      
  <runtime>      
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">      
      <dependentAssembly>      
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />      
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />      
      </dependentAssembly>      
    </assemblyBinding>      
  </runtime>      
</configuration>    

创建IService

如下接口类的C#代码:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Runtime.Serialization;    
using System.ServiceModel;    
using System.ServiceModel.Web;    
using System.Text;    
    
namespace restservice    
{    
    [ServiceContract]    
    public interface IService    
    {    
        [OperationContract]    
        [WebInvoke(Method = "GET",    
             ResponseFormat = WebMessageFormat.Json,    
             BodyStyle = WebMessageBodyStyle.Wrapped,    
             UriTemplate = "login/{username}/{password}")]    
        [return: MessageParameter(Name = "Data")]    
        USER DoLogin(string username, string password);    
    }    
    
        
    public class USER    
    {    
        public string username { get; set; }    
        public string password { get; set; }    
        public string firstname { get; set; }    
        public string lastname { get; set; }    
    }    
}   

添加引用

如果出现任何错误,请添加引用。您需要添加如下库的引用:
image-1665296802797

创建Service方法

我们需要创建一个函数来返回请求。我们将创建一个名为Service的新文件,内容如下所示:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Threading.Tasks;    
    
namespace restservice    
{    
    public class Service : IService    
    {    
        public USER DoLogin(string user, string pass)    
        {    
            try    
            {    
                USER data = new USER();    
    
                if (user == "camellabs" && pass == "camellabs")    
                {    
                    data.username = user;    
                    data.password = pass;    
                    data.firstname = "ecco";    
                    data.lastname = "suprastyo";    
                }    
    
                return data;    
            }    
            catch (Exception ex)    
            {    
                return null;    
            }    
        }    
    }    
}   

编辑Program类

Program类是一个控制台应用程序,它是启动应用程序的主要入口点。它使用WebHostBuilder实例配置并启动web API主机和web服务器。按如下方式编辑Program类:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.ServiceModel;    
using System.ServiceModel.Description;    
using System.ServiceModel.Web;    
using System.Text;    
using System.Threading.Tasks;    
    
namespace restservice    
{    
    class Program    
    {    
        static void Main(string[] args)    
        {    
            WebServiceHost hostWeb = new WebServiceHost(typeof(restservice.Service));    
            ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(restservice.IService), new WebHttpBinding(), "");    
            ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>();    
            stp.HttpHelpPageEnabled = false;    
            hostWeb.Open();    
    
            Console.WriteLine("Service Host started @ " + DateTime.Now.ToString());    
    
            Console.Read();    
        }    
    }    
}    

运行程序

在Microsoft Visual Studio 2015中以调试或发布模式运行应用程序。
测试应用程序(如果已经在浏览器中运行),如下所示:
image-1665297011740

0
广告 广告

评论区