ASP.NET API2 设计 RESTful API 服务端解决跨域

原理:

只需要在消息头中添加一句:
Access-Control-Allow-Origin *

即可.

解决方案是直接在nuget中安装 Microsoft Asp.Net Web Api 2.2 Cross-Origin

然后在App-Start/WebApiConfig.cs下:

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

namespace WAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

即可.

ASP.NET API2 设计 RESTful API

Copyright @ DocsASP.NETASP.NET Web API

微软的官方文档

首先是新建ASP.NET api项目

然后是设计Model

Product.cs

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

namespace WAPI.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(路由)

ProductsController.cs

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

using WAPI.Models;

namespace WAPI.Controllers
{
    public class ProductsController : ApiController
    {
        // XXM => decimal类型小数
        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)
        {
            //容器.FirstOrDefault(Boolean) 返回满足条件的第一个元素,如未找到,返回默认值
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                //ApiController.NotFound()
                //即404界面
                return NotFound();
            }
            //正常返回
            return Ok(product);
        }
    }
}

最后通过编写前端界面,并使用JQuery来实现ajax传输,显示

index.html

<!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>

结果如下所示