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="*" />

 
原文地址:https://www.cnblogs.com/Harvard-L/p/6007856.html