C# webapi服務器,創建自定義的,簡單的web服務器,供遠程接口調用


在Visual Studio 中的NuGet管理器中可以下載安裝,也可以直接在NuGet控制台輸入下面的指令安裝:

 

1
Install-Package HslCommunication

 

 如果需要教程:Nuget安裝教程:http://www.cnblogs.com/dathlin/p/7705014.html

 

組件的完整信息和API介紹參照:http://www.cnblogs.com/dathlin/p/7703805.html   組件的使用限制,更新日志,都在該頁面里面。

本庫的demo源代碼地址:https://github.com/dathlin/HslCommunication

 

 

 

好了,我們開始一步步的說明。如何進行創建功能復雜的web api接口的。先簡單的創建一個服務器對象

		private HttpServer httpServer;                                                     // 當前的Web服務器,支持web api來通信的方式

		private void Start( )
		{
			// 啟動web的服務器
			try
			{
				this.httpServer = new HttpServer( );
				this.httpServer.Start( 8000 );
			}
			catch (Exception ex)
			{
				Console.WriteLine( "Web服務器加載失敗!" + ex.Message );
			}
		}

		// 調用start方法之后,我們打開瀏覽器,輸入 http://127.0.0.1:8000 就可以看到如下的文本 "This is HslWebServer, Thank you for use!"
		// After calling the start method, we open the browser and enter http://127.0.0.1:8000 to see the following text: "This is HslWebServer, Thank you for use!"

  此時我們打開網頁看看

 

通常來說,基本的實例化,返回固定的數據並不能滿足我們的需求,我們需要返回自定義的數據,有一個委托,我們需要自己指定方法.

private HttpServer httpServer;                                                     // 當前的Web服務器,支持web api來通信的方式

private void Start( )
{
    // 啟動web的服務器
    try
    {
        this.httpServer = new HttpServer( );
        this.httpServer.HandleRequestFunc = HandleRequest;
        this.httpServer.Start( 8000 );
    }
    catch (Exception ex)
    {
        Console.WriteLine( "Web服務器加載失敗!" + ex.Message );
    }
}

private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data )
{
    if (request.HttpMethod == "GET")
    {
        return "This is Get Method";
    }
    else if (request.HttpMethod == "POST")
    {
        return "This is Post Method";
    }
    else
    {
        return string.Empty;
    }
}

  

 我們用瀏覽器測試到結果如下

 

 

 如果我們要測試POST操作,我們這時候就就需借助一個軟件了,POSTMAN軟件,如下所示

 

 

 

ok,返回了我們所需的數據了,現在我們更深入一步。決定區分地址

private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data )
{
    if (request.HttpMethod == "GET")
    {
        if (request.RawUrl == "/GetA")
        {
            return "This is GetA Method";
        }
        else if (request.RawUrl == "/GetB")
        {
            return "This is GetB Method";
        }
        else
        {
            return "This is Notsupported Method";
        }
    }
    else if (request.HttpMethod == "POST")
    {
        if (request.RawUrl == "/PostA")
        {
            Console.WriteLine( data );   // data 就是post上來的數據信息
            return "OK";
        }
        return "This is Post Method";
    }
    else
    {
        return string.Empty;
    }
}

 

現在就可以使用地址了

 

 

 POST的情況也是類似的。

 

 

到這里為止,已經可以實現很多高級的功能了,但是我們還需要更高級的功能,比如實現安全驗證,加入賬戶名密碼的驗證,可以這么代碼

private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data )
{
    // 下面的對授權驗證增加用戶名和密碼的操作,當使用瀏覽器登錄的時候,會自動彈出輸入用戶名及密碼的窗口
    // The following operation for adding a username and password for authorization verification will automatically pop up a window for 
    // entering the username and password when logging in with a browser.
    string[] values = request.Headers.GetValues( "Authorization" );
    if (values == null || values.Length < 1 || string.IsNullOrEmpty( values[0] ))
    {
        response.StatusCode = 401;
        response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" );
        return "";
    }

    string base64String = values[0].Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries )[1];
    string accountString = Encoding.UTF8.GetString( Convert.FromBase64String( base64String ) );
    string[] account = accountString.Split( new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries );
    if (account.Length < 2)
    {
        response.StatusCode = 401;
        response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" );
        return "";
    }

    // 此處假定用戶名和密碼限定了 admin 123456
    if (!(account[0] == "admin" && account[1] == "123456"))
    {
        response.StatusCode = 401;
        response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" );
        return "";
    }

    if (request.HttpMethod == "GET")
    {
        if (request.RawUrl == "/GetA")
        {
            return "This is GetA Method";
        }
        else if (request.RawUrl == "/GetB")
        {
            return "This is GetB Method";
        }
        else
        {
            return "This is Notsupported Method";
        }
    }
    else if (request.HttpMethod == "POST")
    {
        if (request.RawUrl == "/PostA")
        {
            Console.WriteLine( data );   // data 就是post上來的數據信息
            return "OK";
        }
        return "This is Post Method";
    }
    else
    {
        return string.Empty;
    }
}

  

 當我們使用瀏覽器的時候,就會自動提示輸入用戶名和密碼

 

 

在這里就輸入上面的用戶名和密碼,就可以登錄了。就可以正常的訪問。如果使用POSTMAN的情況的話。這么操作

 

 

需要將基本的信息填入,才能進行基本的請求。

如果需要返回基本的html信息,可以如下操作

復制private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data )
{
    if (request.HttpMethod == "GET")
    {
        if (request.RawUrl == "/GetA") // 當瀏覽器瀏覽一個網頁的時候,輸入 http://127.0.0.1:6000/GetA 會顯示網絡內容
        {
            response.AddHeader( "Content-type", $"Content-Type: text/html; charset=utf-8" );
            return "<html><head><title>HslWebServer</title></head><body><p style=\"color: red\">這是一個測試的消息內容</p></body></html>";
        }
        else
        {
            return "This is Notsupported Method";
        }
    }
    else if (request.HttpMethod == "POST")
    {
        return "This is Post Method";
    }
    else
    {
        return string.Empty;
    }
}

  

 結果如下

 

 

 

你寫出的API,就可以被任意的第三方程序所調用了,而不用管對方的平台,語言。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM