C# webapi簡單學習


創建WebApi項目:

在VS工具中創建一個ASP.NET Web應用程序

 

選擇Webapi

一個webapi項目就創建好了

這里簡單的寫一個post和get兩種請求的方法,由於post請求參數需要參數體的形式,一般用json作為參數,這里簡單創建一個實體類,放上參數,我這里就放一個,可根據項目自己設置相應的參數

注意的是,post請求的時候,json里的鍵值對 鍵的名字要和實體中的一樣,過來實體接收參數會自動將json值拆分到各個對應的名字上

 

然后先寫post方法,記得要寫請求方式[HttpPost]注意這個參數的寫法

[HttpPost]
public string demo([FromBody]Contact name) 
{
     string nn = name.Name;
     string result = string.Empty;
     result = "您的參數是:" + nn;
     return result;
}

 

Get方法可以直接獲取參數,注意[HttpGet]

[HttpGet]
public string wxs(string name)
{
    string result = string.Empty;
    result = "{Name:\"" + name + "\"}";
    return result;
}

 

一個簡單的webapi就寫完了,現在試試請求這個webapi,我這里用C#控制台應用程序寫一個簡單的調用

為了方便測試,我直接將這個webapi發布到了本機的IIS上

Post請求:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string ss = HttpPost("http://localhost:8097/api/Contact/demo", "{\"Name\":\"zhangsan\"}");

            
            Console.WriteLine(ss);



            Console.ReadLine();
        }






        public static string HttpPost(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }

        }
    }
}

 

Get請求: 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {


            string ss = HttpGet("http://localhost:8097/api/Contact/wxs?name=zhangsan");

            Console.WriteLine(ss);



            Console.ReadLine();
        }


        public static string HttpGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }


    }
}

 

 


免責聲明!

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



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