首页 > 技术文章 > WebApi

birds-zhu 2018-09-13 16:24 原文

WebApi1

WebApi

一般创建webapi程序是在通过网站,IIS这种方式,我这里做实验使用OWIN这种方式,用控制台程序来实现的.

1.新建一个控制台程序WebApiServer

2.添加类Startup,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiServer
{
public class Startup
{

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(name: "DefaultApi",
            routeTemplate: "api/{Controller}/{id}",
            defaults: new
            {
                id = RouteParameter.Optional
            });

        app.UseWebApi(config);
    }

}
}

很明显,现在IAppBuilder,HttpConfiguration是找不到引用的,得使用NuGet来找,而且还非常不好找,因为名字不同啊,NuGet这个问题很让我困扰,不知道大家有没有同感.反正我是添加了了无数次才搞定这个引用. 用NuGet添加

Microsoft.aspnet.webapi 和 Microsoft.aspnet.webapi.Owin

 

然后直接添加System.web的引用,终于不报错了,O(∩_∩)O....

3.添加一个Student类

namespace WebApiServer
{
    class Student
    {
       public string ID { get; set; }
        public string Name { set; get; }

        public DateTime Birthday { set; get; }

    }
}

4.添加一个StudentController类

namespace WebApiServer
{
    class StudentController
    {
        public Student GetStudentByID(string id)
        {
            return new Student()
            {
                ID = id,
                Name = "Lily",
                Birthday = DateTime.Now.AddYears(-10)
            };
        }
    }
}

5.在Main函数中添加

         var url = "http://localhost:8777/";

        var startOpts = new StartOptions(url);
        using (WebApp.Start<Startup>(startOpts))
        {
             Console.WriteLine("不依托IIS的webapi;" + url);
            Console.ReadLine();
        }

需要添加,Microsoft.Owin.Hosting;

 

6.启动服务

这时候启动,会报错System.MissingMemberException: 'The server factory could not be located for the given input: Microsoft.Owin.Host.HttpListener' 需要添加 Microsoft.Owin.Host.HttpListener

 

 添加后再次启动,启动成功.这时候打开浏览器URL:http://localhost:8777/api/Student/GetStudentByID 错误如图

 

这是因为找不到Controller,修改StudentController,让其继承ApiController

class StudentController: ApiController
{
  //todo
}

再次启动,可惜还是不行.把StudentController,Student修改成public,再来,当然成功了,如图

 

p6

试试这个URL:http://localhost:8777/api/Student/GetStudentByID?id=5,见

 

p7(参数问题后面在研究)

7.客户端调用

建立一个控制台程序,这面这段代码可以调用:

        string baseAddress = "http://localhost:8777/";
        HttpClient client = new HttpClient();

        var response = client.GetAsync(baseAddress + "api/student").Result;

        Console.WriteLine(response);

        Console.WriteLine(response.Content.ReadAsStringAsync().Result);

        Console.ReadLine();

 

推荐阅读