创建一个Web API 项目

在本教程中,你将使用ASP.NET Web API 来创建一个web API 并返回产品列表。 网页前端使用jQuery 显示结果。

选择ASP.NET Web Application,新建名ProductsApp

在弹出框里选择空的模板,并把Web API勾选上,点击OK。

注意

你也可以创建一个“Web API"模板,这个模板将提供ASP.NET MVC帮助页面等框架。但我使用空模板作为教程,因为我想展示Web API没有MVC时的运作,一般来说不需要用MVC来使用API。

添加一个Model

一个模型是一个对象,表示应用程序中的数据。ASP.Web API模型可以自动序列化JSON、XML或其他格式,然后序列化数据写入HTTP响应消息的主体。只要客户端可以读取序列化格式,它可以对对象进行反序列化。大多数客户可以解析XML或JSON。此外,客户端可以表明它希望的格式通过设置HTTP请求中的Accept标头信息。

让我们首先创建一个简单的模型,代表了一个产品。

如果没有可见的解决方案资源管理器,单击“视图”菜单,选择“解决方案资源管理器”。在解决方案资源管理器中,右键单击模型文件夹。从上下文菜单中,选择Add然后选择类。

类名取"Product"

C#
namespace ProductsApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}

添加一个控制器Controller

在Web API,控制器是一个对象处理HTTP请求。我们将添加一个控制器,可以返回产品列表或指定的单个产品ID。

请注意
如果你有使用ASP.MVC,您已经熟悉控制器。Web API控制器类似MVC控制器,但是继承ApiController类而不是控制器类。

在解决方案资源管理器中,右键单击控制器文件夹。选择Add然后选择控制器。

In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.

控制器名字 "ProductsController". 点击 Add.

ProductsController.cs 在Controllers文件夹内

 
C#
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http; namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
}; public IEnumerable<Product> GetAllProducts()
{
return products;
} public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}

复制例子代码到controller类中。

定义了2个方法返回产品

  • GetAllProducts 方法返回类型IEnumerable<Product>
  • GetProduct 方法查找单个产品通过ID

就是这样!你有一个工作的web API。控制器上的每个方法对应于一个或多个uri:

Controller Method URI
GetAllProducts /api/products
GetProduct /api/products/id

例如 GetProduct 方法,  id 在 URI 是一个占位符,假设id是5: api/products/5.

调用Web API 通过 Javascript and jQuery

在本节中,我们将添加一个HTML页面,使用AJAX调用web API。我们将使用jQuery AJAX调用和结果更新页面。

在解决方案资源管理器中,右键单击项目并选择添加,然后选择新的项目。

选择HTML Page item. Name the page "index.html".

html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product App</title>
</head>
<body> <div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/products'; $(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
}); function formatItem(item) {
return item.Name + ': $' + item.Price;
} function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
</body>
</html>

得到一个产品列表

发送HTTP GET请求 "/api/products".

html
$(document).ready(function () {
// Send an AJAX request
$.getJSON(apiUrl)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});

通过ID得到产品

发送HTTP GET 请求"/api/products/id"

JavaScript
function find() {
var id = $('#prodId').val();
$.getJSON(apiUrl + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}

运行应用

按下F5 开始 调试应用,页面如下

1

输入ID

如果你输入一个无效的ID,将返回错误

使用F12 来查看HTTP Request and Response

当你使用一个HTTP服务,它可以是非常有用的HTTP请求,请求消息。你可以通过使用Internet Explorer 9的F12开发工具。从Internet Explorer 9,按F12打开工具。单击网络选项卡和媒体开始捕捉。现在回到web页面,按F5重新加载web页面。Internet Explorer将捕获浏览器和web服务器之间的HTTP流量。摘要视图显示一个页面的所有网络流量:

定位相对URI的条目“api /产品/”。选择这个条目并单击详细视图。在细节视图,有选项卡以查看请求和响应头和身体。例如,如果您单击请求头选项卡,您可以看到客户端请求“application / json”Accept标头。

如果你单击响应主体选项卡,您可以看到产品列表是如何序列化为JSON。其他浏览器也有类似的功能。另一个有用的工具是小提琴手,web调试代理。您可以使用Fiddler查看HTTP流量,并构成HTTP请求,这让你完全控制请求中的HTTP头。

开始一个简单的ASP.NET Web API 2 (C#)的更多相关文章

  1. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  2. 一个ASP.NET Web API 2.0应用

    在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用 由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.N ...

  3. 使用ASP.NET web API创建REST服务(二)

    Creating a REST service using ASP.NET Web API A service that is created based upon the architecture ...

  4. 使用ASP.NET web API创建REST服务(三)

    本文档来源于:http://www.cnblogs.com/madyina/p/3390773.html Creating a REST service using ASP.NET Web API A ...

  5. 如何让ASP.NET Web API的Action方法在希望的Culture下执行

    在今天编辑推荐的<Hello Web API系列教程--Web API与国际化>一文中,作者通过自定义的HttpMessageHandler的方式根据请求的Accep-Language报头 ...

  6. 学习ASP.NET Web API框架揭秘之“HTTP方法重写”

    最近在看老A的<ASP.NET Web API 框架揭秘>,这本书对于本人现阶段来说还是比较合适的(对于调用已经较为熟悉,用其开发过项目,但未深入理解过很多内容为何可以这样“调用”).看到 ...

  7. Asp.Net Web API 2第十六课——Parameter Binding in ASP.NET Web API(参数绑定)

    导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html. 本文主要来讲解以下内容: ...

  8. Parameter Binding in ASP.NET Web API(参数绑定)

    Parameter Binding in ASP.NET Web API(参数绑定) 导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnbl ...

  9. 使用HttpClient消费ASP.NET Web API服务

    本篇体验使用HttpClient消费ASP.NET Web API服务,例子比较简单. 依次点击"文件","新建","项目". 选择&quo ...

随机推荐

  1. shell笔记-常用

    shell提取文件名: http://blog.csdn.net/u011544778/article/details/50773053 一.使用${} 1.${var##*/}该命令的作用是去掉变量 ...

  2. object detection[SSD]

    0. 背景 经过了rcnn,spp,fast rcnn, faster rcnn,yolo,这里又到了ssd模型. faster rcnn的贡献是将候选框区域提取的部分也集成到CNN中去,并且与对象的 ...

  3. Scripts may close only the windows that were opened by it

    关闭当前窗体报以下js错误: Scripts may close only the windows that were opened by it (脚本只能关闭由它打开的窗口) 使用场景,在js中关闭 ...

  4. RabbitMQ详解(三)------RabbitMQ的五种队列

    上一篇博客我们介绍了RabbitMQ消息通信中的一些基本概念,这篇博客我们介绍 RabbitMQ 的五种工作模式,这也是实际使用RabbitMQ需要重点关注的. 这里是RabbitMQ 官网中的相关介 ...

  5. 【Java面试宝典】深入理解JAVA虚拟机

    一.运行时数据区域 线程隔离:线程隔离的意思,就是给不同的线程多分配的资源用,以做到不争用. 线程共享:线程共享就是资源只有一个没有办法分配更多,只能共享. Java虚拟机管理的内存包括几个运行时数据 ...

  6. configure: error: cannot guess build type; you must specify one解决方法

    原文地址:https://blog.csdn.net/hebbely/article/details/53993141 1.configure: error: cannot guess build t ...

  7. BZOJ4289 Tax 最短路建模

    给定一个带边权的无向图,求1到n的最小代价路径.经过一个点的代价是路径上这个点的入边和出边的较大权值. \(n \le 100000, m \le 200000\). 一般的建图是考虑每个点,其入边和 ...

  8. 543A - Writing Code(二维动态规划)

    题意:现在要写m行代码,总共有n个文件,现在给出第i个文件每行会出现v[i]个bug,问你在bug少于b的条件下有多少种安排 分析:定义dp[i][j][k],i个文件,用了j行代码,有k个bug 状 ...

  9. Could not open connection

    意思是不能打开JDBC连接,如果代码没写错的话就是服务没打开,开一下服务就行了,oracle两个必开的服务:OracleServiceORCL和OracleOraDb11g_home2TNSListe ...

  10. Git push提交时报错Permission denied(publickey)...Please make sure you have the correct access rights and the repository exists.

    一.git push origin master 时出错 错误信息为: Permission denied(publickey). fatal: Could not read from remote ...