本篇文章主要介绍了asp.net MVC下使用rest的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
前言
最近做了下个MVC的项目,需要用到rest接口,与java写的应用程序通信,包括数据的接收和发送,那么我将用实用的角度来全面的讲解一下它的使用方法
一、创建rest服务
首先创建一个Asp.Net Web应用程序(我这里用的是Visual Studio 2013,它已经内置了Web API2)。
在出来的模板中选择Empty(空项目),并勾选WebAPI。点击确定后,就创建了一个空的WebAPI服务。
此时只有一个空项目,还没有任何功能,在进行下一步之前,首先我们来看一下REST的基本操作模型,大致可以分为如下四种:
POST — 创建资源
GET — 检索资源
PUT — 更新资源
DELETE — 删除资源
非常经典的CRUD模型。在Web API中实现这样一个的模型是非常简单的,直接使用向导建一个Controller即可
如果用传统的向导,记得把向导后面的那个1给去掉:
默认的模板内容如下:
public class ValuesController : ApiController { // GET api/<controller> publicIEnumerable<string> Get() { returnnewstring[] { "value1", "value2" }; } // GET api/<controller>/5 publicstring Get(int id) { return"value"; } // POST api/<controller> publicvoid Post([FromBody]string value) { } // PUT api/<controller>/5 publicvoid Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 publicvoid Delete(int id) { } }
这其实已经帮我们实现了一个最基本的服务了,这样别人就可以访问我们的服务中的方法
二、调用其它应用程序的rest服务
1、RestClient类
为了便于使用,我们需要封装客房端的rest类,话不多说,我们直接上这个类的代码:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace OilDigital.A2_A27.Web { public class RestClient { public string EndPoint { get; set; } //请求的url地址 public HttpVerb Method { get; set; } //请求的方法 public string ContentType { get; set; } //格式类型:我用的是application/json,text/xml具体使用什么,看需求吧 public string PostData { get; set; } //传送的数据,当然了我使用的是json字符串 public RestClient() { EndPoint = ""; Method = HttpVerb.GET; ContentType = "application/x-www-form-urlencoded"; PostData = ""; } public RestClient(string endpoint) { EndPoint = endpoint; Method = HttpVerb.GET; ContentType = "application/json"; PostData = ""; } public RestClient(string endpoint, HttpVerb method) { EndPoint = endpoint; Method = method; ContentType = "application/json"; PostData = ""; } public RestClient(string endpoint, HttpVerb method, string postData) { EndPoint = endpoint; Method = method; ContentType = "application/json"; PostData = postData; } public RestClient(string endpoint, HttpVerb method, string postData, string contentType) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; } public string MakeRequest() { return MakeRequest(""); } public string MakeRequest(string parameters) { var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters); request.Method = Method.ToString(); request.ContentType = ContentType; if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)//如果传送的数据不为空,并且方法是post { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果传送的数据不为空,并且方法是put { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseValue = string.Empty; if (response.StatusCode != HttpStatusCode.OK) { var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); } // grab the response using (var responseStream = response.GetResponseStream()) { if (responseStream != null) using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } return responseValue; } } } public enum HttpVerb { GET, //method 常用的就这几样,当然你也可以添加其他的 get:获取 post:修改 put:写入 delete:删除 POST, PUT, DELETE } }
2、RestClient类使用
有了这个类后我们就很方便的去调用别人的rest服务了,使用方法如下:
①,基本的调用:
var client = new RestClient(); string endPoint = @"http:\\myRestService.com\api\"; var client = new RestClient(endPoint); var json = client.MakeRequest();
②,如果你想带入参数
var json = client.MakeRequest("?param=0");
③,使用最多的方式
var client = new RestClient(); client.EndPoint = @"http:\\myRestService.com\api\"; ; client.ContentType = "application/json"; client.Method = HttpVerb.POST; client.PostData = "{postData: value}"; var json = client.MakeRequest();
三、我自己项目中的使用
1、首先我测试了一下,我调用我自己的rest服务的带参的get方法,当然我这里传的参数直接写在url的后面在,参数形式是string,所以接收的get方法的形参也要改成string,这样你就
可以接收到传过去的参数了。当然别人应用程序也是可以调的。只要把url给他就行了。
/// <summary> /// 从接口中获取当前用户所有信息 /// </summary> /// <param name="userId">用户ID</param> /// <returns>json对象</returns> public string GetCurrentUserInfo() { string userId = GetCurrentUserId(); string endPoint = "http://localhost:100/Api/RestService/"+userId; var client = new RestClient(endPoint); var userInfo = client.MakeRequest(); return userInfo; }
2、接下来,我要开始试用java写的应用程序下的rest服务了,我通过我传过去的用户ID获取到了用户的所有信息,当然我在项目中使用了缓存技术,还将返回回来的json字符串转换成了json对象,以便我后面好用linq对其进行操作,关于linq to json 可以参考我的linq专题相关文章 ,我在项目中的代码是酱子的:
/// <summary> /// 从接口中获取用户所有信息 /// </summary> /// <param name="userId">用户ID</param> /// <returns></returns> public static JObject CacheUser() { try { string currentUser = GetCurrentUserId(); if (HttpRuntime.Cache.Get("user$" + GetCurrentUserId()) == null) { string endPoint = "http://66.66.66.666:6666/DASBASE/restServices/dataCollectionService/getUserPermissions"; string postData = "jsonData={\"userCode\": \"kfry\",\"systemId\": \"1E1A7AC94BFC41D4BEBED8942EB69689\"}"; var client = new RestClient(endPoint, HttpVerb.POST, postData, "application/x-www-form-urlencoded"); var u = client.MakeRequest(); JObject userInfo = JObject.Parse(u); //插入缓存 HttpRuntime.Cache.Insert("user$" + currentUser, userInfo, null, System.DateTime.UtcNow.AddMinutes(30), TimeSpan.Zero); } return (JObject)HttpRuntime.Cache.Get("user$" + GetCurrentUserId()); } catch (Exception ex) { throw new ApplicationException("获取用户信息出错:"+ex.Message); } }
The above is the detailed content of Introducing the method of using rest under asp.net MVC. For more information, please follow other related articles on the PHP Chinese website!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
