一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于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. //读取配置文件(属性文件)的工具类-ConfigManager

    package com.pb.news.util; import java.io.IOException;import java.io.InputStream;import java.sql.Resu ...

  2. kali切换字符界面模式和切换图形界面模式

    我也是走了很多弯路,下面把正确的命令写出来,网上的不是说不正确,是linux命令做出了更改 Systemd是一种新的linux系统服务管理器 它替代了init, 直接上命令吧! 切换至字符界面 sud ...

  3. Rsync:一个很实用的文件同步命令

    sync是Linux系统下的文件同步和数据传输工具,可用于同步文件.代码发布 1.安装. yum install -y xinetd yum insatll -y rsync 2.配置 打开rsync ...

  4. 使用TinyXML进行XML操作

    本例基于TinyXML实现XML的自动解析和创建,由于本人是菜鸟刚入门,例子中添加了enum.struct.vector.map.list的常见用法,首先添加6个tinyxml工程文件,然后设置调试参 ...

  5. JAVA高并发

    一.JAVA高级并发 1.5JDK之后引入高级并发特性,大多数的特性在java.util.concurrent 包中,是专门用于多线程发编程的,充分利用了现代多处理器和多核心系统的功能以编写大规模并发 ...

  6. 华为OJ之放苹果

    题目描述: 把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法.输入每个用例包含二个整数M和N.0<=m< ...

  7. php 设计模式之策略模式

    策略模式:定义算法,并将其封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户. 步骤:1.抽象策略角色:定义接口或抽象类 2.具体策略角色:实现该接口(抽象类),即具体的算法实现 ...

  8. 【linux相识相知】磁盘分区及文件系统管理详解

    磁盘,提供持久的数据存储,它不像我们的内存,如果突然断电了,在内存中的数据一般都会被丢掉了,内存中的数据在保存的时候,会被写到硬盘里面,磁盘也是一种I/O设备. 我们都知道磁盘分区完成之后,还要进行格 ...

  9. phpunit实践笔记

    phpunit成为单元测试的代名词已成为共识, 但很多在实际编写测试过程中遇到的很多问题通过手册.网上搜索都很难找到相关资料, 大部分都得通过查看源代码和实践的代码经验解决.欢迎大家拍砖.(在此之前请 ...

  10. 连接池报错 Proxool Provider unable to load JAXP configurator file: proxool.xml

    上篇博文讲到简易配置 proxool 连接池:http://www.cnblogs.com/linnuo/p/7232380.html 由于把说明注释留在了 proxool.xml 配置文件里导致配置 ...