一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于RaidDevelopmentFramework 我有着自己的见解在应用到实际的框架中确实挺好用的,但是还是存在一部分的问题。这个需要后期进行不断的完善以及修改。最近一段时间对于这个WebApi 我又进行重新的研究和学习。

ASP.NET Web API是用于构建可以从任何客户机访问(包括浏览器和移动设备)的HTTP服务的框架。 它是一种基于.NET Framework构建RESTFUL应用程序的理想平台。

二.那么WebApi 如何在传统的应用程序中进行使用和结合到.NET FrameWork 来进行使用。

三.ASP.NET Web API特性

  1. Web API 是一个构建基于restful服务的理想平台。

  2. Web API 是基于Asp.Net,支持ASP.Net 请求/响应管道

  3. Web API 有良好的路由机制。

  4. Web API 支持不同格式的响应数据,内置支持JSON、XML BSON格式。

  5. Web API 可以部署非常方便。

  6. Web API框架包括新的HttpClient,他可以与Web API服务器通信。HttpClient可以在ASP.Net MVC服务器端,Windows Form应用程序,控制台应用程序或其他应用程序中使用。

四. 关于

ASP.NET Web API版本

web api版本 支持的.net framework版本 对应的MVC版本 支持的VS版本
Web API 1.0 .NET Framework 4.0 ASP.NET MVC 4 VS 2010
Web API 2.0 .NET Framework 4.5 ASP.NET MVC 5 VS 2012,VS 2013

ASP.NET Web API VS WCF

web api wcf
开源,支持.net framework 支持.net framework
只支持HTT通信协议 支持HTTP,TCP,UDP以及自定义通信协议等
良好的路由机制来匹配url与对应接口 基于Attribute来匹配
使用类似于Asp.net MVC的路由规则和Controller模型 使用Service,契约等
不支持可靠的消息传递和事务。 支持可靠的消息传递和事务。
可以使用HttpConfiguration 来配置Web Api,不一定需要web.config配置 使用web.config和Attribute来配置一个服务
适合构建RESTful服务。 支持构建RESTful服务但有局限性

五. 下面通过进行对于CRUD 的方法使用来进行说明。

 #region 使用客户端进行调用WebApi来进行实现
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Hosting;
using System.Net.Http.Formatting;
using System.Net.Http;
using System.Net;
using WebAPI.Models;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.IO; namespace ConsoleClient
{
class Program
{ private readonly static JsonMediaTypeFormatter formatter =
GlobalConfiguration.Configuration.Formatters
.Where(f =>
{
return f.SupportedMediaTypes.Any
(v => v.MediaType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase));
})
.FirstOrDefault() as JsonMediaTypeFormatter;
static void Main(string[] args)
{
//GetAll();
//GetFristMessage();
//Update();
//Delete();
Console.WriteLine(DecryptDES("zqindFI5UNSKrp5weiuIm5cScBM=", "Y+Z7bE1/DoLCWxchX9eeyg=="));
//AddCustomerMessage();
Console.ReadLine();
} /// <summary>
/// 获取列表的信息
/// </summary>
private static async void GetAll()
{
HttpClient _httpClient = new HttpClient();
string _url = string.Format(@"http://localhost:3536/api/Customers");
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
var data = await _httpClient.GetAsync(_url);
using (var httpClient = new HttpClient(handler))
{
var response = await data.Content.ReadAsAsync<List<Customers>>();
var responseModel = await httpClient.GetAsync(_url);
if (responseModel.IsSuccessStatusCode == true)
{
foreach (var items in response.ToList())
{
Console.WriteLine("用户名:" + items.ContactName + "公司名称:" + items.CompanyName);
}
Console.WriteLine("==============================================");
var jsonData = await responseModel.Content.ReadAsStringAsync();
Console.WriteLine(jsonData);
var customerList = JsonConvert.DeserializeObject<List<Customers>>(jsonData);
foreach (var items in customerList.ToList())
{
Console.WriteLine("用户名:" + items.ContactName + "公司名称:" + items.CompanyName);
}
}
}
} /// <summary>
///获取单个的数据的信息
/// </summary>
private static async void GetFristMessage()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
var response = await httpClient.GetAsync(@"http://localhost:3536/api/Customers/Get?id=2"); var customer = response.Content.ReadAsAsync<Customers>().Result;
var jsonData = response.Content.ReadAsStringAsync().Result;//将其转化为JSON
var json = await response.Content.ReadAsStringAsync(); //调用此方法将其转化为JSON效果和上面一样
Console.WriteLine(json);
var customerModel = JsonConvert.DeserializeObject<Customers>(await response.Content.ReadAsStringAsync());
if (response.IsSuccessStatusCode == true)
{
Console.WriteLine("用户名称:" + customerModel.ContactName + "公司名称:" + customerModel.CompanyName);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.RequestMessage);
Console.WriteLine("用户名称:" + customer.ContactName + "公司名称:" + customer.CompanyName);
}
}
} /// <summary>
///进行更新数据
/// </summary>
private static async void Update()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var httpClient = new HttpClient(handler))
{
try
{
Customers customer = new Customers();
customer.Address = "江苏";
customer.City = "南京";
customer.CompanyName = "南京***有限公司";
customer.Country = "中国";
customer.CustomerID = ;
customer.Phone = "****";
customer.ContactName = "李四"; var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"ContactName","张三"},
{"Phone","***"},
{"Address","江苏南京"},
{"Country","中国"},
{"CompanyName","江苏**"}
}); //两种方式的返回的结果是一致的。但是对于其中的传输的方式确实不一致的。
var response = await httpClient.PutAsync<Customers>(@"http://localhost:3536/api/Customers/Get?id=123", customer, formatter);
//var response = await httpClient.PutAsync(@"http://localhost:3536/api/Customers/Get?id=123",content); var customerModel = response.Content.ReadAsAsync<Customers>().Result;
var jsonData = response.Content.ReadAsStringAsync().Result;
var json = await response.Content.ReadAsStringAsync();
//将返回的JSON 数据进行反序列化成为对象
var customerData = JsonConvert.DeserializeObject<CustomersModel>(jsonData);
Console.WriteLine(customerData.CompanyName);
Console.WriteLine("=========================================");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
if (response.IsSuccessStatusCode == true)
{
if (customerModel != null)
{
Console.WriteLine("用户名称:" + customerModel.ContactName + "公司名称:" + customerModel.CompanyName);
}
} }
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
} /// <summary>
///根据ID进行删除的操作
/// </summary>
private static async void Delete()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
var response =await httpClient.DeleteAsync(@"http://localhost:3536/api/Customers/Delete?id=123");
Console.WriteLine("删除操作的状态码:"+response.StatusCode);
}
} /// <summary>
/// 添加客户的信息
/// </summary>
public static async void AddCustomerMessage()
{
var handler = new HttpClientHandler() {AutomaticDecompression=DecompressionMethods.GZip };
Customers customer = new Customers();
customer.Address = "江苏";
customer.City = "南京";
customer.CompanyName = "南京****";
customer.Country = "中国";
customer.CustomerID = ;
customer.Phone = "***";
customer.ContactName = "赵六";
using (var httpClient=new HttpClient(handler))
{
var response = await httpClient.PostAsync<Customers>(@"http://localhost:3536/api/Customers",customer,formatter);
if (response.IsSuccessStatusCode==true)
{
var data= response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsAsync<Customers>().Result.CompanyName);
}
}
} public static async void Test(string url= "http://localhost:3536/api/Customers", string json="")
{
var handler = new HttpClientHandler() { AutomaticDecompression=DecompressionMethods.GZip};
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using (var httpClient=new HttpClient(handler))
{
var response =await httpClient.PostAsync(url, httpContent);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
} public class CustomersModel
{
public int CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
} public static string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = { 0x13, 0x24, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
} }
}

2017.08-20 22:19:23

以上内容全部是基于原创 如需转载请标明!!!!谢谢合作。

WebApi 的CRUD 的方法的应用的更多相关文章

  1. 创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图

    创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图 创建CRUD动作方法及视图 参照VS自带的基架(Scaffold)系统-MVC Controller with view ...

  2. WebAPi添加常用扩展方法及思维发散

    前言 在WebAPi中我们通常需要得到请求信息中的查询字符串或者请求头中数据再或者是Cookie中的数据,如果需要大量获取,此时我们应该想到封装一个扩展类来添加扩展方法,从而实现简便快捷的获取. We ...

  3. PCB DotNetCore Swagger生成WebAPI文档配置方法

    在.net framework框架下可以使用WebApiTestClientWebApi生成WebAPI接口文档与方便接口测试用,而在DotnetCore却没有找到这个工具了,baidu查找一下发现有 ...

  4. WebAPI 2参数绑定方法

    简单类型参数 Example 1: Sending a simple parameter in the Url [RoutePrefix("api/values")] public ...

  5. C# WebApi Xml序列化问题解决方法:“ObjectContent`1”类型未能序列化内容类型“application/xml;charset=utf-8"的响应正文。...

    在调试一个WebApi程序时,出现下面错误: 通过分析怀疑是未添加序列化属性引起的,实体类改为下面结构后,问题依旧: 通过查阅资料和不断尝试,修改实体类的属性注解搞定:

  6. 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null

    问题描述: POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null ...

  7. SQLSERVER单表CRUD通用方法

    一.适用场景 ①当你书写简单的增删改查心累了 ②当你的项目不考虑并发.高性能 ③当你追求更快速的开发效率 ④当你的业务只涉及单表 二.代码展示 ①单表Insert public bool Insert ...

  8. WebApi 参数绑定方法

    WebAPI 2参数绑定方法   简单类型参数 Example 1: Sending a simple parameter in the Url 01 02 03 04 05 06 07 08 09 ...

  9. ssh整合思想 Spring与Hibernate和Struts2的action整合 调用action添加数据库 使用HibernateTemplate的save(entity)方法 update delete get 等方法crud操作

    UserAction类代码: package com.swift.action; import com.opensymphony.xwork2.ActionSupport; import com.sw ...

随机推荐

  1. mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)

    下面示例在mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现 Demo的基础上进行优化 以新增一个用户为例子,原UserMapper.xml配置如下: < ...

  2. PAT-1099(Build A Binary Search Tree)

    题目见这里 分析:分四步进行 1)根据给定的结点情况建二叉树  2)对输入的键值排序(asending) 3)对二叉树中序遍历,同时对应赋key值 4)层次遍历(队列应用) 题目并不困难,但是我误入了 ...

  3. CCS学习(三)

    边框样式  边框线 dorder-style (top 上: bottom 下:  left 左: right 右)  样式:none | hidden | dotted | dashed | sol ...

  4. linux centos7 安装redis

    首先看官方教程:http://redis.io/download Download, extract and compile Redis with: $ wget http://download.re ...

  5. python selenium自动化之-环境搭建

    安装python和pip上述文章有介绍,在这里不在赘述.直接安装seleinum pip3 install selenium 安装完成以后, pip3 show selenium 显示 Name: s ...

  6. jvm学习006 jvm内存结构分配

    主要内容如下: JVM启动流程 JVM基本结构 内存模型 编译和解释运行的概念 一.JVM启动流程: JVM启动时,是由java命令/javaw命令来启动的. 二.JVM基本结构: JVM基本结构图: ...

  7. WIN10下设置惠普HP1050等打印机打印颜色,只打黑白或彩色

    今天同事问了一个问题,如何在WIN10下,设置惠普打印机只打印黑白, 上网搜了下,没有找到任何信息,只有在WIN8前系统设置的内容,经过几番折腾,得出此文. WIN10下设置惠普HP1050等打印机打 ...

  8. Android - 电池状态

    为了解决电池图标的问题,顺带看了看电池信息的获取方法 :自己写了一个小栗子,来验证一下效果 电池的信息,一般都在BatteryManager里面,信息是用广播发出的.我们更新信息需要一个广播接收器 注 ...

  9. 用caffe一步一步实现人脸检测

    学习深度学习已有一段时间了,总想着拿它做点什么,今天终于完成了一个基于caffe的人脸检测,这篇博文将告诉你怎样通过caffe一步步实现人脸检测.本文主要参考唐宇迪老师的教程,在这里感谢老师的辛勤付出 ...

  10. __main() 和 main() 【转】

    因为我们通常在BOOTLOADER中都已做好了比较细致的初始化工作,包括代码的搬运,所以我们最好别再调用库函数__main(),因为__main()作为ADS集成好的库函数,会对系统进行初始化设置,可 ...