一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于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. MinGW(GCC)编译DLL文件

    这两天用CB(Code::Blocks)写个小程序,要编译出DLL供VB(6)使用.CB使用mingw-gcc作为编译器,在库文件的产出上跟VC.VS之类的IDE略有不同. 由于C语言的基础知识不是太 ...

  2. JSP基本语法总结【2】九大内置对象

    内置对象也称为内建对象,隐含对象,即无需声明,直接可以在JSP中使用的java对象.JSP的内置对象就是把最常用.重要的几个对象直接创建了. JSP有9大内置对象:Request,Response, ...

  3. Mac之OS系统下搭建JavaEE环境 <四> 之IntelliJ IDEA 的内存优化

    1.代开IntelliJ IDEA 的显示内容 2. 打开idea.vmoptions文件 路径为Contens——bin——idea.vmoptions 修改之前会复制一份备份原配置 原配置 修改后 ...

  4. Java 数据库编程 ResultSet 的 使用方法

    结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同时还具有操纵数据的功能,可能完成对数据的更新等. 结果集读取数据 ...

  5. raft如何实现Linearizable Read

    Linearizable Read通俗来讲,就是读请求需要读到最新的已经commit的数据,不会读到老数据. 对于使用raft协议来保证多副本强一致的系统中,读写请求都可以通过走一次raft协议来满足 ...

  6. Tomcat解压版配置详解(Tomcat8示例)

    注:请在JDK安装后操作以下内容 1.  下载Tomcat解压缩安装包 http://mirror.bit.edu.cn/apache/tomcat/tomcat-8/v8.0.45/bin/apac ...

  7. Java编程思想总结笔记Chapter 2

    本章介绍Java程序的基本组成部分,体会到Java中几乎一切都是对象. 第二章   一切都是对象 目录: 2.1 用引用操纵对象 2.2 必须由你创建所有对象 2.3 永远不需要销毁对象 2.4 创建 ...

  8. 【3D计算机图形学】变换矩阵、欧拉角、四元数

    [3D计算机图形学]变换矩阵.欧拉角.四元数 旋转矩阵.欧拉角.四元数主要用于:向量的旋转.坐标系之间的转换.角位移计算.方位的平滑插值计算.   一.变换矩阵: 首先要区分旋转矩阵和变换矩阵: 旋转 ...

  9. docker学习笔记--重基础使用

    最近一直在研究Elasticsearch,后来部门的同事遇到了一个docker集群的未授权访问漏洞,于是稍微看了一下docker进行了一下基本的入门,本文把自己学习docker的过程进行了一个详细的记 ...

  10. Oracle 11g OCM 考试大纲

    考试大纲共分9部分.   一.Server Configuration 服务器配置 1  Create the database 创建数据库 2  Determine and set sizing p ...