当前位置:网站首页>C # create self host webservice

C # create self host webservice

2022-07-06 02:46:00 flysh05

C# Create word managed Web service .

1. Create a project , Originally used ConsoleApp From hosting one WebService.

Enter the project name  ConsoleApp_SelfHost, Solution name :SelfHostWebServiceTest

2. Create data model classes , DataModel.cs

public class DataModel

{

public int Id { get; set; }

public string Name { get; set; }

public string DeviceType { get; set; }

}

3.  install Microsoft.AspNet.WebApi.SelfHost Third party component

4. Create a data model control class DataModelController.cs

Add reference :

using System.Net;

using System.Web.Http;

public class DataModelController:ApiController

{

DataModel[] datas = new DataModel[]

{

new DataModel { Id = 1, Name = “DELL”, DeviceType = “PC” },

new DataModel{ Id = 2, Name = “HuaWei”, DeviceType = “Phone” },

new DataModel{ Id = 3, Name = “SanDisk”, DeviceType = “Assceory” }

};

public IEnumerable GetAllItems()

{

return datas;

}

public DataModel GetItemById(int id)

{

var item = datas.FirstOrDefault((i) => i.Id == id);

if (item == null)

{

throw new HttpResponseException(HttpStatusCode.NotFound);

}

return item;

}

public IEnumerable GetItemsByType(string deviceType)

{

return datas.Where(i => string.Equals(i.DeviceType, deviceType,

StringComparison.OrdinalIgnoreCase));

}

}

5. stay Program Created in the main program HttpSelfHostServer

Add reference to background code

using System.Web.Http;

using System.Web.Http.SelfHost;

class Program

{

static void Main(string[] args)

{

var config = new HttpSelfHostConfiguration(“http://localhost:9001”);

config.Routes.MapHttpRoute(

“API Default”, “api/{DataModelController}/{id}”,

new { id = RouteParameter.Optional });

using (HttpSelfHostServer server = new HttpSelfHostServer(config))

{

server.OpenAsync().Wait();

Console.WriteLine(“Press Enter to quit.”);

Console.ReadLine();

}

}

}

Run to start the service .

原网站

版权声明
本文为[flysh05]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132359428404.html