码迷,mamicode.com
首页 > Windows程序 > 详细

web api

时间:2017-04-29 09:48:25      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:fmb   oci8   koch   gcj   wol   ken   hue   wado   setting   

WebAPI的内容部分直接转自官方文档,英语水平有限,不做翻译,

发布网站在本文的后半部分

 

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products.

Software versions used in the tutorial

Create a Web API Project

In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.

技术分享

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Name the project "ProductsApp" and click OK.

技术分享

In the New ASP.NET Project dialog, select the Empty template. Under "Add folders and core references for", check Web API. Click OK.

技术分享

 

Adding a Model

A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

Let‘s start by creating a simple model that represents a product.

If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.

 

 

技术分享

技术分享

Name the class "Product". Add the following properties to the Product class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProductsApp
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public String Category { get; set; }
        public decimal Price { get; set; }
    }
}

 

Adding a Controller

In Web API, a controller is an object that handles HTTP requests. We‘ll add a controller that can return either a list of products or a single product specified by ID.

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.

技术分享

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

技术分享

In the Add Controller dialog, name the controller "ProductsController". Click Add.

技术分享

The scaffolding creates a file named ProductsController.cs in the Controllers folder.

技术分享

note:You don‘t need to put your contollers into a folder named Controllers. The folder name is just a convenient way to organize your source files. 

If this file is not open already, double-click the file to open it. Replace the code in this file with the following:

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProductsApp;

namespace ProductsApp
{
    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 },
            new Product { Id = 4, Name = "Dog", Category = "Animal", Price = 50M },
        };
        
        //IEnumerable是一个公开枚举数,该枚举数支持在非泛型集合上进行简单的迭代
        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);
        }

    }
}

 

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.

The controller defines two methods that return products:

  • The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
  • The  GetProduct method looks up a single product by its ID.

That‘s it! You have a working web API.  Each method on the controller corresponds to one or more URIs:

Controller MethodURI
GetAllProducts /api/products
GetProduct /api/products/id

For the GetProduct method, the id in the URI is a placeholder. For example, to get the product with ID of 5, the URI is api/products/5.

Calling the Web API with Javascript and jQuery

In this section, we‘ll add an HTML page that uses AJAX to call the web API. We‘ll use jQuery to make the AJAX calls and also to update the page with the results.

In Solution Explorer, right-click the project and select Add, then select New Item.

技术分享

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".

技术分享

Replace everything in this file with the following:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <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>

 There are several ways to get jQuery. In this example, I used the Microsoft Ajax CDN. You can also download it from http://jquery.com/, and the ASP.NET "Web API" project template includes jQuery as well.

Getting a List of Products

To get a list of products, send an HTTP GET request to "/api/products".

The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.

$(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‘));
            });
        });
});

Getting a Product By ID

To get a product by ID, send an HTTP GET  request to "/api/products/id", where id is the product ID.

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);
        });
}

We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

Running the Application

Press F5 to start debugging the application. The web page should look like the following:

技术分享

To get a product by ID, enter the ID and click Search:

技术分享

If you enter an invalid ID, the server returns an HTTP error:

技术分享

Using F12 to View the HTTP Request and Response

When you are working with an HTTP service, it can be very useful to see the HTTP request and request messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:

技术分享

Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested "application/json" in the Accept header.

技术分享

If you click the Response body tab, you can see how the product list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. You can use Fiddler to view your HTTP traffic, and also to compose HTTP requests, which gives you full control over the HTTP headers in the request.

以上转自:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

 

由于返回结果为xml文件,我这里进行了一下处理,转换成json格式

技术分享

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;

namespace ProductsApp
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //xml转json
            ConfigureApi(GlobalConfiguration.Configuration);
        }
        void ConfigureApi(HttpConfiguration config)
        {
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
}

 

 

下面是网页的发布过程:

1.打开你的网站项目,右键项目,生成一下,如果不报错就继续下一步

技术分享

2.右键项目,点击发布

技术分享

3.弹出网站发布设置面板,【配置文件】可以使用默认,或者新建,点击【下一步】;

技术分享

4.在【发布方法】中选【文件系统】,这样我们可以发布到自己指定的本机上,选择【目标位置】,即你要发布到哪个文件夹;

技术分享

5.点击【下一步】,在【配置】中,要选择【发布模式】(Release称为发布版本,它进行了优化,使得程序在代码大小和运行速度上都是最优的,以便用户很好地使用。Debug 通常称为调试版本,它包含调试信息,并且不作任何优化,便于程序员调试程序);

技术分享

6.点击【下一步】,进入发布前的预览界面;

技术分享

7.点击发布即可以发布你指定的文件夹中;

 

此时的发布只是生成了发布所需要的文件,要能狗访问还需要有服务器;这里我就在本机的IIS上发布

1.首先打开ISS,

win7的步骤 :开始菜单----搜索框---输入IIS,在结果中,找到IIS快捷方式

技术分享

win10:直接在小娜那里输入IIS即可

 

2.进入IIS主界面,右键网站,选择“添加网站”。

技术分享

 

3.在“添加网站”对话框中,添加网站名称。

技术分享

 

4.点击应用程序池选择,设置网站的应用程序池(默认新建一个和网站名称一样的应用程序池),当然你也可以选择其他应用程序池,新手推荐用默认程序池就可以了,如图:

技术分享

 

5.接下来选择项目存放的路径,项目文件夹必须是项目的根目录,选择完毕,点击确定。

技术分享

 

6.配置网站的IP地址和端口,如果本机有独立的IP地址,可以选择固定的IP,如果本机只是测试环境,可以填写127.0.0.1    设置完成,点击确定。

技术分享

 

7.最后一步设置网站的默认页面:点击新建完成的网站,在右边栏目中,找到“默认文档”

技术分享

 

8.点击“默认文档”,弹出窗口中,右键---添加----输入设置为主页面的文件名,然后确定,OK,部署网站就完成了。

技术分享

 

9.最后测试一下网站是否部署成功:网站名称,右键,选择管理网站,点击浏览。

技术分享

10.我的运行结果,局域网下,如果要别人能访问,吧localhost换成自己的ip即可

技术分享

 

最后,发布过程中会遇到很多错误

1.HTTP 错误 500.19 - Internal Server Error 解决方案

技术分享

 技术分享

 

 2.“/”应用程序中的服务器错误

 技术分享

 方法:

技术分享

 

 3.HTTP 错误 500.21 - Internal Server Error 解决方案

原因:在安装Framework v4.0之后,再启用IIS,导致Framework没有完全安装

解决:开始->所有程序->附件->鼠标右键点击“命令提示符”->以管理员身份运行->%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

 新系统(win8,win10)运行%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i 会出现操作系统版本不支持此选项

技术分享

解决方法:

控制面板 - 程序和功能 - 启动或关闭windows功能 - Internet Information services - 万维网服务 - 应用程序开发功能

 勾选:

1、ASP.NET 3.5

2、ASP.NET 4.6

3、ISAPI扩展

4、ISAPI筛选器

5、.NET Extensibility 3.5

6、.NET Extensibility 4.6

 

4.HTTP 错误 404.8 - Not Found       http 错误 404.3 not found

控制面板 - 程序和功能 - 启动或关闭windows功能 - Internet Information services - 万维网服务 - 应用程序开发功能

技术分享

技术分享

重启IIS。

 

个人建议应用程序开发功能可以全部勾选上,一般的问题都是可以解决的

还有所有错误,微软都有相应的解决方法,举个例子:(图从网上来,错误解决了,忘记截图了,我圈出来的地方就是解决的办法)

 

技术分享

web api

标签:fmb   oci8   koch   gcj   wol   ken   hue   wado   setting   

原文地址:http://www.cnblogs.com/qixuejia/p/6784201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!