你的位置:首页 > ASP.net教程

[ASP.net教程]ASP.NET WEB API 初探

本文初步介绍如何简单创建一个ASP.NET Web Api 程序。

 

Web Api 顾名思义就是一个Api接口,客户端可调用此接口进行业务操作。此类应用与 ASP.NET  web服务(即使用扩展名.asmx的web服务文件)有一定的相似之处,又有大不同,

ASP.NET Web Api 主要是基于ASP.NET MVC 框架。

废话少说,现在开始。

 

我用的开发工具是Visul studio 2015。

 

1. 创建ASP.NET Web Api 项目。

 

 

 

改项目名称为DRMWebAPI,可得如下项目结构。

至此,API项目创建完毕。下面,我们添加新的Controller。在Controllers文件夹下添加NewdealerController.cs文件,如下图:

 

添加完成之后,我想用post方法传送参数的方式来调用这个接口。所以,我添加了一个类库DRMModel,如下图。

 

 

类库中有一个主类 NewDealer,主类NewDealer 包含Dealer,Contact,RDaddress,HouseAddress,SendAddress五个类。

各个类代码如下:

Dealer.cs

 public class Dealer  {    public string RecruiterID { get; set; }    public string Recruiter { get; set; }    public string NationalID { get; set; }    public string dealer_name { get; set; }    public string sex { get; set; }    public string BirthYear { get; set; }    public string BirthMonth { get; set; }    public string BirthDay { get; set; }  }

Contact.cs

 public class Contact  {    public string nightphonezonecode { get; set; }    public string nightphone { get; set; }    public string dayphonezonecode { get; set; }    public string dayphone { get; set; }    public string dayphoneext { get; set; }    public string mobilephone { get; set; }    public string email { get; set; }    public string occupation { get; set; }    public string occupation_sel { get; set; }    public string RecommenderID { get; set; }    public string RecommenderNationalID { get; set; }    public string Recommender { get; set; }    public string EINVOICE { get; set; }    public string DONATEINVOICE { get; set; }  }

RDaddress.cs

 public class RDaddress  {    public string OLDMAILNO1 { get; set; }    public string OLDADDRESS1 { get; set; }  }

HouseAddress.cs

public class HouseAddress  {    public string selzipcode { get; set; }    public string selprovince { get; set; }    public string selcity { get; set; }    public string seladdr { get; set; }    public string sellane { get; set; }    public string selalley { get; set; }    public string selno { get; set; }    public string selfl { get; set; }    public string selroom { get; set; }    public string selroomnum { get; set; }    public string selrecipient { get; set; }  }

 

SendAddress.cs

 public class SendAddress  {    public string selzipcode1 { get; set; }    public string selprovince1 { get; set; }    public string selcity1 { get; set; }    public string seladdr1 { get; set; }    public string sellane1 { get; set; }    public string selalley1 { get; set; }    public string selno1 { get; set; }    public string selfl1 { get; set; }    public string selroom1 { get; set; }    public string selroomnum1 { get; set; }    public string selrecipient1 { get; set; }  }

构造完毕之后,在NewdealerController.cs文件添加如下代码:

using System.Web;using System.Web.Mvc;using System.Net.Http;using System.Web.Http;using System.Text;namespace DRMWebAPI.Controllers{  public class NewdealerController : ApiController  {    //post        public string Add([FromBody]DRMModel.NewDealer newDealer)    {      return newDealer.Dealer.dealer_name;    }  }}

在这里要说明一下,调用ASP.NET Web API 接口可传json格式的数据,API会自动把json数据转换为C#类型,前提是json格式要正确。

分析NewdealerController中的Add方法,可知,当我们传DRMModel.NewDealer json格式数据时,接口会返回newDealer.Dealer.dealer_name。

好了,那么怎么访问这个接口呢?

我们可以查看App_Start 下的 WebApiConfig.cs 文件。

using System;using System.Collections.Generic;using System.Linq;using System.Web.Http;namespace DRMWebAPI{  public static class WebApiConfig  {    public static void Register(HttpConfiguration config)    {      config.Routes.MapHttpRoute(        name: "DefaultApi",        routeTemplate: "api/{controller}/{action}/{id}",        defaults: new { id = RouteParameter.Optional }      );    }  }}

此文件定义了API的访问路径,如上所示,访问NewdealerController中的Add方法的路径为 (域名地址/IP)/api/Newdealer/add。

 

下面,我们尝试调用这个接口,我在HomeController.cs文件中加入如下代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Net;using System.Text;using System.IO;namespace DRMWebAPI.Controllers{  public class HomeController : Controller  {    public ActionResult Index()    {            string postdata = "{\"Dealer\":{\"RecruiterID\":\"1\",\"Recruiter\":\"2\",\"NationalID\":\"2\",\"dealer_name\":\"啊哈哈哈\",\"sex\":\"1\",\"BirthYear\":\"1\",\"BirthMonth\":\"1\",\"BirthDay\":\"1\"},\"Contact\":{\"nightphonezonecode\":\"1\",\"nightphone\":\"1\",\"dayphonezonecode\":\"1\",\"dayphone\":\"1\",\"dayphoneext\":\"1\",\"mobilephone\":\"1\",\"email\":\"1\",\"occupation\":\"1\",\"occupation_sel\":\"1\",\"RecommenderID\":\"1\",\"RecommenderNationalID\":\"1\",\"Recommender\":\"1\",\"EINVOICE\":\"1\",\"DONATEINVOICE\":\"1\"},\"RDaddress\":{\"OLDMAILNO1\":\"1\",\"OLDADDRESS1\":\"1\"},\"HouseAddress\":{\"selzipcode\":\"1\",\"selprovince\":\"1\",\"selcity\":\"1\",\"seladdr\":\"1\",\"sellane\":\"1\",\"selalley\":\"1\",\"selno\":\"1\",\"selfl\":\"1\",\"selroom\":\"1\",\"selroomnum\":\"1\",\"selrecipient\":\"1\"},\"SendAddress\":{\"selzipcode1\":\"1\",\"selprovince1\":\"1\",\"selcity1\":\"1\",\"seladdr1\":\"1\",\"sellane1\":\"1\",\"selalley1\":\"1\",\"selno1\":\"1\",\"selfl1\":\"1\",\"selroom1\":\"1\",\"selroomnum1\":\"1\",\"selrecipient1\":\"1\"}}";            string pageHtml = "";      var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:55706//api/Newdealer/add");      httpWebRequest.ContentType = "text/json";      httpWebRequest.Method = "POST";      using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))      {                streamWriter.Write(postdata);        streamWriter.Flush();        streamWriter.Close();      }      var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();      using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))      {        pageHtml = streamReader.ReadToEnd();      }      ViewData["pram1"] = pageHtml;      return View();    }  }}

代码是模拟浏览器的Post提交数据,提交到http://localhost:55706//api/Newdealer/add 的地址里。

其中postdata是我自己定义的NewDealer 类的json格式数据。至于类与json数据如何转换,请自行百度。

然后,我在View文件夹添加Home文件夹,再添加Index.aspx文件。

添加代码:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %><!DOCTYPE html><html><head runat="server">  <meta name="viewport" content="width=device-width" />  <title>Index</title></head><body>  <div>    <%= ViewData["pram1"] %>  </div></body></html>

根据以上,当我打开Home/Index时,页面应该会输出postdata这个json格式数据中的\"dealer_name\":\"啊哈哈哈\",即页面会输出:  啊哈哈哈

如下图:

Demo下载地址:http://files.cnblogs.com/files/JinvidLiang/DRMWebAPI.zip