WebApi-寄宿方式注意事項

所謂的寄宿方式,就是把服務從原來的容器(iis、appache)中提取出來通過宿主程序來控制其啓動,這樣的好處就是避免了對服務器(容器)的依賴,實現靈活控制,但在實際開發中尤其是新手容易忽略的地方,這裏做個簡單的示例,記錄一下便於以後自查。
  • 首先建立一個公共各類庫 Common,用於存放實體類。編寫一個實體類 Contact
namespace Common
{
    public class Contact
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string PhoneNo { get; set; }
        public string EmailAddress{get;set;}
        public string Address { get; set; }
    }
}

  • 接着在建立一個類庫 SelfHost,用於編寫WebApi 控制器(爲了讓宿主調用,把WebAPI服務放在類庫中實現,這和WCF 是一樣的)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Common;
using System.Threading;
using Newtonsoft.Json;
using System.Web.Http.Cors;

namespace WebApi
{
    [EnableCors(origins:"*",headers:"*",methods:"*")]  //爲了解決跨域問題,這裏引用的Cors 要保持和宿主中一致,Newtonsoft.JSon 也是如此
    public class ContactsController:ApiController
    {
        static List<Contact> contacts;
        static int counter = 2;
        public ContactsController()
        {
            contacts = new List<Contact> {
                new Contact{ Id="1001",Name="張三",PhoneNo="13663782541",EmailAddress="[email protected]",Address="河南南陽"},
                new Contact{ Id="1002",Name="李四",PhoneNo="13683782542",EmailAddress="[email protected]",Address="河南信陽"}
            };
        }
        [HttpGet]
        public IEnumerable<Contact> Get(string Id = null) {
            return contacts.Where(c => c.Id == Id||string.IsNullOrEmpty(Id));
        }
        [HttpPost]
        public List<Contact> Post(dynamic obj) {
            Interlocked.Increment(ref counter);
            Contact contact = new Contact {
                Id = counter.ToString("D3"),
                Name = obj.Name,
                PhoneNo=obj.PhoneNo,
                EmailAddress=obj.EmailAddress,
                Address=obj.Address

            };
            contacts.Add(contact);
            return contacts;
        }
        [HttpDelete]
        public List<Contact> Delete(string Id) {
            contacts.Remove(contacts.First(c => c.Id == Id));
            return contacts;
        }

    }
}

  • 最後編寫宿主程序,這裏以控制檯程序爲例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Web.Http.SelfHost;
using System.Reflection;
using System.Web.Http.Cors;
namespace SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost/selfhost/api/contacts";   // 提供給客戶端參考的地址
            Assembly.Load("WebApi,Version=1.0.0.0,Culture=neutral,PublicToken=null");
            HttpSelfHostConfiguration configuration = new   //這裏的configuration 和原始WebAPI 的Glob.asxa 中的config 對象是一樣的,都是用來爲當前的WebApi服務提供配置信息 HttpSelfHostConfiguration("http://localhost/selfhost");  //這裏的地址是基地址,即類似原始WebApi中的 localhost:8080
            configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);  //刪除默認的xml格式
            configuration.Formatters.Add(new JsonMediaTypeFormatter());   //增加JSON格式 
            configuration.EnableCors(); //啓用跨域
            using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration)) {
                httpServer.Configuration.Routes.MapHttpRoute(  //設置服務器的路由信息
                    name:"DefaultApi",
                    routeTemplate:"api/{controller}/{id}",
                    defaults: new { id=RouteParameter.Optional}
                    );
                httpServer.OpenAsync().Wait();  //啓動服務
                Console.WriteLine("WebApi 服務器已啓動...");
                Console.WriteLine($"地址:{url}");
                Console.Read();
            }
        }
    }
}

  • 啓動服務
    image

  • 瀏覽器訪問
    image

  • 測試跨域
    HTHML代碼

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-1.10.2.js"></script>
		<script>
		
			function f1(){
				$.ajax({
					type:"get",
					url:"http://localhost:58208/api/home",
					data:{},
					async:true,
					success:function(res){
						$("#txt").append(JSON.stringify(res)+"\n");
						
					},
					error:function(err){
						alert(JSON.stringify(err));
					}
					
				});
				
			}
			
           function f2(){
           	$.ajax({
           		type:"get",
           		url:"http://localhost:58208/api/home",
           		data:{"name":"張三"},
           		async:true,
           		success:function(res){
           			$("#txt").append(JSON.stringify(res)+"\n");
           			
           		},
           		error:function(err){
           			alert(JSON.stringify(err));
           			
           		}
           	});

           }
		function f3() {
		
			$.ajax({
				type:"post",
				url:"http://localhost:58208/api/home",
				contentType:"application/json",
				data:JSON.stringify({"name":"張三","age":12}),
				async:true,
				success:function(res){
					$("#txt").append(JSON.stringify(res)+"\n");
				},
				error:function(err){
					alert(JSON.stringify(err));
					
				}
			});
		
			
		}
		function f4(){
			$.ajax({
				type:"get",
				url:"http://localhost/selfhost/api/contacts",
				async:true,
				success:function(res){
					$("#txt").append(JSON.stringify(res));
					
				},
				error:function(err){
					alert(JSON.stringify(err));
					
				}
			});
			
		}
		</script>
	</head>
	<body>
		<div>
			<button onclick="f1()">測試1-Get無參</button>
			<button onclick="f2()">測試2-Get有參</button>
			<button onclick="f3()">測試3-Post動態參數</button>
			<button onclick="f4()">寄宿服務測試-Get</button>
		</div>
		<div>
			<textarea id="txt" rows="25" cols="38" ></textarea>
		</div>
	</body>
</html>

測試效果:
image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章