一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于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. Chrome浏览器扩展开发系列之十八:扩展的软件国际化chrome.i18n API

    i18n是internationalization 的简写,这里将讨论软件国际化的问题.熟悉软件国际化的朋友应该知道,软件国际化要求,页面中所有用户可见的字符串都必须置于资源属性文件中.资源属性文件中 ...

  2. 虚拟机配置静态IP地址

    使用VMware配置虚拟机静态IP地址 一.安装好虚拟后在菜单栏选择编辑→ 虚拟网络编辑器,打开虚拟网络编辑器对话框,选择Vmnet8 Net网络连接方式,随意设置子网IP,点击NAT设置页面,查看子 ...

  3. multipath多路径实验01-构建iscsi模拟环境

    multipath多路径实验01-构建iscsi模拟环境 前几天跟同事网上闲聊技术,吐槽之前自己没有配置过多路径的经历,虽然多路径的配置过程很简单,职责划分也应是主机或存储工程师来搞定,DBA只需要直 ...

  4. 决策树(C4.5)原理

    决策树c4.5算法是在决策树ID3上面演变而来. 在ID3中: 信息增益 按属性A划分数据集S的信息增益Gain(S,A)为样本集S的熵减去按属性A划分S后的样本子集的熵,即 在此基础上,C4.5计算 ...

  5. (转)Linux命令grep

    场景:grep命令在文件搜索中经常会使用到,所以熟练掌握该命令对于日常日志搜索相当有必要! Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.g ...

  6. python数据库学习--Mysql

    摘要: Python使用mysql需要安装驱动,有两种1)mysqldb 2)umysql  ,两者都是开源,具体区别不详,umysql没用过 一.mysqldb 安装MySQL驱动--http:// ...

  7. taskctl 软件集群安装部署

    TASKCTL的集群部署实际上是通过Server服务节点和多个Agent代理节点部署在网络环境中来实现的.在完成之前的单机部署之后,我们已经成功安装了一个Server节点了.接下来我们再介绍一下怎么安 ...

  8. php的laravel框架使用心得

    最近在做一项目,是基于laravel的后台api,用于与手机交互的,数据采用json格式.下面说下怎样在两周内把一个新框架或者语言用的得心应手. 项目采用laravel5.4+dingoapi+jwt ...

  9. 微信小程序实现“鲜肉APP”首页效果

    项目地址http://git.oschina.net/djcx/WeiXinXiaoChengXu/tree/master 如果您觉得不错,记得给一个star 由于微信小程序目前是当下趋势,正好昨天弄 ...

  10. 微信客户端+微信公众平台+新浪云SAE+Arduino+WS100(控制LED)

    第一步:准备 1.智能手机微信客户端或微信电脑版 2.注册微信公众平台 https://mp.weixin.qq.com 3.注册新浪账号 http://www.sinacloud.com 4.拥有一 ...