Asp.net (2) Business processing interface project (Web Api)
Introduction
ApiAs a business logic provider, it carries the core logic of the project and therefore has relatively high logic complexity. Under such a premise, how to simplify code writing, how to standardize and unify the writing style and logic specifications, and how to improve the maintainability and scalability of the code. It becomes important to build projects with high cohesion and low coupling.
The example is an enterprise-level project, FrameworkThe picture is as follows
dler) is rewritten, the validity of the request is judged, and the signature requirements are preprocessed. Client: defines a unified
interface calling method is used by the calling end, simplifying and unifying the use of the interface. Ctrl layer: As a direct provider of services, it directly provides an interface similar to RestFul style on the server (it feels strict RestFul style, requiring a complete domain
ModelDriver , the actual situation is always unsatisfactory, and the domain abstraction ability is not enough), obtain the request data, call FilterFilter on demand, make further judgments, and call
Model. Layer: As the business model layer, it provides the actual operation of business logic. Use a unified entity model and connect it to Ibatis for data operations. The specific code structure is as follows:
##Api-UML.jpg
The following is a detailed introduction and description of each module Code example:
Entity library project code example
The project structure is as follows:
##entity.jpg
main
module, as an entity model, the simple code is as followspublic class User { public int Id { get; set; } public string NickName { get; set; } public string Avatar { get; set; } }Request, the request structure model, uses the generic interface to connect the request class and the return class, which achieves control inversion role.
public abstract class AbstractRequest { public bool ValidateParameters() { //公用方法示例,验证参数合法性 } } public interface IRequest<t> where T:AbstractResponse { //获取接口名称 string GetApiName(); //获取接口编码 string GetApiCode(); } //获取User信息的请求结构定义 public class GetUserRequest:AbstractRequest,IRequest<getuserresponse> { public int Id { get; set; } public string GetApiName() { return "User.GetUserDetail"; } public string GetApiCode() { return "User001"; } }</getuserresponse></t>Response module, as the return type of the request, defines a unified return structure to facilitate consumers to judge and process consistent return codes.
public abstract class AbstractResponse { //返回码 public int Code { get; set; } //报错信息 public string Message { get; set; } } public class GetUserResponse:AbstractResponse { public User User { get; set; } }Service project code exampleThe project structure is as follows:
service.jpg
public interface IUserService { GetUserResponse GetUser(int id); } public class BaseService { //protected SqlInstance sqlInstance; public BaseService() { //sqlInstance=new SqlInstance(); //实例化数据库连接 //... } //... } public class UserService:BaseService,IUserService { public GetUserResponse GetUser(int id) { //链接数据库获取数据 //... throw new NotImplementedException(); } }Security
Class library
Code exampleThe class library only handles security
issues and adds permission judgment at the api request entry . Use the method of rewriting Http requests.Code examplepublic class MyHandler : DelegatingHandler
{
protected async override Task<httpresponsemessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string> keyEnumerable;
var t1 = request.Headers.TryGetValues("key", out keyEnumerable);
var key = keyEnumerable.FirstOrDefault();
if (!true)//验证类似于token的权限
{
return await Task.Factory.StartNew<httpresponsemessage>(
() => new HttpResponseMessage(HttpStatusCode.Forbidden)
{
Content = new StringContent("error message")
});
}
//如果有signature,判断,并加结果标志,没有的话,清除signature相关信息,防止伪造。
//.....
return await base.SendAsync(request, cancellationToken);
}
}</httpresponsemessage></string></httpresponsemessage>
The abstracted permission judgment can be directly called to the webapi end and added to the
routing
security management
and interface permission control. To learn the permission control of WeChat, several interfaces have been roughly determined:Interface permissions.png
The judgments of these permissions are all placed Centralized management is done in Security. The interface definition only needs to be used to judge the legality of the corresponding logic.
Code example:public class UserController : ApiController { private IUserService userService; public UserController() { userService=new UserService(); } [Signature]//安全签名过滤器判断 [HttpPost] public GetUserResponse GetUser(GetUserRequest request) { //参数判断,安全性判断等等 var ret = userService.GetUser(request.Id); return ret; } }
The above is an example interface for obtaining user information. As for the routing configuration as the interface entrance, you need to judge the legality of the request. The routing configuration code is as follows:
public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}", defaults: new { id = RouteParameter.Optional } ); //添加的代码,添加http请求的入口处理 config.MessageHandlers.Add(new MyHandler()); }Client class library code exampleClient class library defines the public methods called by the interface.
1. Use generic interfaces to encapsulate the request class and return class to simplify the writing of calling code.
2. And make consumers call the interface through the proxy class, avoiding cross-domain problems.3. Consumer calls all agree to use a unified class library, so that the log processing is unified, and the returned errors can also be defined consistently.
Code examples are as follows:
public interface IClient { T Execute<t>(IRequest<t> request) where T : AbstractResponse; } public class DefaultClient:IClient { private readonly string appKey; private readonly string appSecret; private readonly string baseUrl = "http://localhost:16469/api/"; private readonly bool isNeedLogFile = false; private readonly LogFile logFile; public static readonly string SecureHeaderAppKey = "secure_head_appkey"; public static readonly string SecureHeaderSignature = "secure_head_signature"; public DefaultClient() { baseUrl = ConfigurationManager.AppSettings["service_base_url"]; appKey = ConfigurationManager.AppSettings["app_key"]; appSecret = ConfigurationManager.AppSettings["app_secret"]; isNeedLogFile = "1".Equals(ConfigurationManager.AppSettings["client_log_file"]); logFile = new LogFile("client_log_path"); logFile.SubPath = appKey; } public DefaultClient(string serviceBase, string code, string key) { baseUrl = serviceBase; appKey = code; appSecret = key; } public T Execute<t>(IRequest<t> request) where T : AbstractResponse { var webRequest = (HttpWebRequest)WebRequest.Create(baseUrl + request.GetApiName()); webRequest.Method = "POST"; string reqJson; string sign; using (Stream rs = webRequest.GetRequestStream()) { reqJson = JsonConvert.SerializeObject(request); byte[] reqBytes = Encoding.UTF8.GetBytes(reqJson); rs.Write(reqBytes, 0, reqBytes.Length); rs.Close(); } webRequest.ContentType = "application/json"; webRequest.Headers.Add(SecureHeaderAppKey, appKey); sign = ComputeHash(appKey, appSecret, reqJson); webRequest.Headers.Add(SecureHeaderSignature, sign); //记录日志 if (isNeedLogFile) { logFile.Log(string.Format("[{0}] 请求内容: {1}", request.GetApiCode(), reqJson)); logFile.Log(string.Format("[{0}] 请求签名: {1}", request.GetApiCode(), sign)); } try { using (var resp = (HttpWebResponse)webRequest.GetResponse()) { try { Stream respStream = resp.GetResponseStream(); if (respStream == null) { throw new WebException("GetResponseStream returned null"); } var streamReader = new StreamReader(respStream); string respStr = streamReader.ReadToEnd(); //记录日志 if (isNeedLogFile) { logFile.Log(string.Format("[{0}] 响应内容: {1}", request.GetApiCode(), respStr)); } return JsonConvert.DeserializeObject<t>(respStr); } catch (Exception e) { //记录日志 if (isNeedLogFile) { logFile.Log(string.Format("[{0}] 响应错误: {1}", request.GetApiCode(), e.Message)); } throw new ApplicationException(e.Message, e); } } } catch (WebException e) { var errMsg = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); //记录日志 if (isNeedLogFile) { logFile.Log(string.Format("[{0}] 请求错误: {1}", request.GetApiCode(), errMsg)); } throw new APIServiceException(errMsg); } } private string ComputeHash(string key, string secret, string body) { return Convert.ToBase64String( SHA1.Create().ComputeHash(Encoding.Default.GetBytes(string.Concat(key, secret, body.Trim())))); } }</t></t></t></t></t>
以上就是Api项目端的各个核心环节的详细介绍。
接下来会对调用端即前端进行简单的介绍。Asp.net(三)Web端展示
The above is the detailed content of Asp.net (2) Business processing interface project (Web Api). For more information, please follow other related articles on the PHP Chinese website!

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.