• WebApi调用及发布


    //Controller
     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);
            }
        }
    //Models
      public class Product
        {
           public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        }
    
    

    WebApiConfig.cs Web API 路由

    默认方法:GetAllProducts(); "api/{controller}/{id}"  http://localhost/api/products

    调用自定义方法:GetAllProducts(); "api/{controller}/{action}/{id}"  http://localhost/api/products/GetAllProducts

    把此API部署IIS上

    C#后台代码调用例子:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Async="true"  %>

    因后台调用是异步需要加 Async="true" 

    public string Get(){

    string url = "http://IIS端口/api/products/GetAllProducts";

    HttpClient client = new HttpClient();

    //返回数据格式XML或JSON
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
    //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json");

    HttpResponseMessage response = client.GetAsync(url).Result;
    Task<string> xx = response.Content.ReadAsStringAsync();

    string xx1 = response.Content.ReadAsStringAsync().Result;

    }

    返回数据XML:

    <arrayofproduct xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/API2.Models">
    <product>
    <category>Groceries</category>
    <id>1</id>
    <name>Tomato Soup</name>
    <price>1</price>
    </product>
    <product>
    <category>Toys</category>
    <id>2</id>
    <name>Yo-yo</name>
    <price>3.75</price>
    </product>
    <product>
    <category>Hardware</category>
    <id>3</id>
    <name>Hammer</name>
    <price>16.99</price>
    </product>
    </arrayofproduct>

    返回JSON:

    [{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0}
    ,{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75}
    ,{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

    前台调用直接写ajax就可以完成。

    如果是跨域调用时前台页需要加此标签(此代码可以解决跨域调用数据返回错误问题,ajax使用jsonp格式)

    <meta http-equiv="Access-Control-Allow-Origin" content="*" />

     
  • 相关阅读:
    POJ 1426 Find The Multiple(数论——中国同余定理)
    POJ 2253 Frogger(Dijkstra变形——最短路径最大权值)
    POJ 3790 最短路径问题(Dijkstra变形——最短路径双重最小权值)
    POJ 3278 Catch That Cow(模板——BFS)
    HDU 1071 The area
    HDU 1213 How Many Tables(模板——并查集)
    POJ 1611 The Suspects
    light oj 1214 Large Division
    POJ 1258 Agri-Net(Prim算法求解MST)
    POJ 2387 Til the Cows Come Home(模板——Dijkstra算法)
  • 原文地址:https://www.cnblogs.com/Harvard-L/p/6007856.html
Copyright © 2020-2023  润新知