Table of Contents
Introduction
Entity library project code example
The project structure is as follows:
security management
1. Use generic interfaces to encapsulate the request class and return class to simplify the writing of calling code.
Home Backend Development C#.Net Tutorial Asp.net (2) Business processing interface project (Web Api)

Asp.net (2) Business processing interface project (Web Api)

Apr 04, 2017 pm 03:32 PM
asp.net web api interface

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

Asp.net (2) Business processing interface project (Web Api)

##api layer.jpg

Security: The Http request (Override DelegatingHan

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:

Asp.net (2) Business processing interface project (Web Api)
##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:

Asp.net (2) Business processing interface project (Web Api)##entity.jpg

Do

main

module, as an entity model, the simple code is as follows

public class User
{
      public int Id { get; set; }
      public string NickName { get; set; }
      public string Avatar { get; set; }
}
Copy after login
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";
        }
    }
Copy after login
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; }
    }
Copy after login
Service project code example

The project structure is as follows:

Asp.net (2) Business processing interface project (Web Api)service.jpg

Code Example:

 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();
        }
    }
Copy after login
Security

Class library

Code example
The class library only handles security
issues and adds permission judgment at the api request entry . Use the method of rewriting Http requests.

Code example

The abstracted permission judgment can be directly called to the webapi end and added to the
routing

configuration code.

WebApi project example

As the actual definition of the interface, webapi defines the actual rules of the interface file, and makes corresponding
security management
and interface permission control. To learn the permission control of WeChat, several interfaces have been roughly determined:

Asp.net (2) Business processing interface project (Web Api)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;
        }

    }
Copy after login

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());
}
Copy after login
Client class library code example

Client 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()))));
        }
    }
Copy after login

以上就是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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard Mar 12, 2024 pm 04:34 PM

When we assemble the computer, although the installation process is simple, we often encounter problems in the wiring. Often, users mistakenly plug the power supply line of the CPU radiator into the SYS_FAN. Although the fan can rotate, it may not work when the computer is turned on. There will be an F1 error "CPUFanError", which also causes the CPU cooler to be unable to adjust the speed intelligently. Let's share the common knowledge about the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard. Popular science on the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard 1. CPU_FANCPU_FAN is a dedicated interface for the CPU radiator and works at 12V

Common programming paradigms and design patterns in Go language Common programming paradigms and design patterns in Go language Mar 04, 2024 pm 06:06 PM

As a modern and efficient programming language, Go language has rich programming paradigms and design patterns that can help developers write high-quality, maintainable code. This article will introduce common programming paradigms and design patterns in the Go language and provide specific code examples. 1. Object-oriented programming In the Go language, you can use structures and methods to implement object-oriented programming. By defining a structure and binding methods to the structure, the object-oriented features of data encapsulation and behavior binding can be achieved. packagemaini

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

Solution to NotImplementedError() Solution to NotImplementedError() Mar 01, 2024 pm 03:10 PM

The reason for the error is in python. The reason why NotImplementedError() is thrown in Tornado may be because an abstract method or interface is not implemented. These methods or interfaces are declared in the parent class but not implemented in the child class. Subclasses need to implement these methods or interfaces to work properly. How to solve this problem is to implement the abstract method or interface declared by the parent class in the child class. If you are using a class to inherit from another class and you see this error, you should implement all the abstract methods declared in the parent class in the child class. If you are using an interface and you see this error, you should implement all methods declared in the interface in the class that implements the interface. If you are not sure which

Application of interfaces and abstract classes in design patterns in Java Application of interfaces and abstract classes in design patterns in Java May 01, 2024 pm 06:33 PM

Interfaces and abstract classes are used in design patterns for decoupling and extensibility. Interfaces define method signatures, abstract classes provide partial implementation, and subclasses must implement unimplemented methods. In the strategy pattern, the interface is used to define the algorithm, and the abstract class or concrete class provides the implementation, allowing dynamic switching of algorithms. In the observer pattern, interfaces are used to define observer behavior, and abstract or concrete classes are used to subscribe and publish notifications. In the adapter pattern, interfaces are used to adapt existing classes. Abstract classes or concrete classes can implement compatible interfaces, allowing interaction with original code.

Insight into Hongmeng system: actual function measurement and usage experience Insight into Hongmeng system: actual function measurement and usage experience Mar 23, 2024 am 10:45 AM

As a new operating system launched by Huawei, Hongmeng system has caused quite a stir in the industry. As a new attempt by Huawei after the US ban, Hongmeng system has high hopes and expectations. Recently, I was fortunate enough to get a Huawei mobile phone equipped with Hongmeng system. After a period of use and actual testing, I will share some functional testing and usage experience of Hongmeng system. First, let’s take a look at the interface and functions of Hongmeng system. The Hongmeng system adopts Huawei's own design style as a whole, which is simple, clear and smooth in operation. On the desktop, various

Inner class implementation of interfaces and abstract classes in Java Inner class implementation of interfaces and abstract classes in Java Apr 30, 2024 pm 02:03 PM

Java allows inner classes to be defined within interfaces and abstract classes, providing flexibility for code reuse and modularization. Inner classes in interfaces can implement specific functions, while inner classes in abstract classes can define general functions, and subclasses provide concrete implementations.

Java interfaces and abstract classes: revealing the inner connection between them Java interfaces and abstract classes: revealing the inner connection between them Mar 04, 2024 am 09:34 AM

Interface Interface defines abstract methods and constants in Java. The methods in the interface are not implemented, but are provided by the class that implements the interface. The interface defines a contract that requires the implementation class to provide specified method implementations. Declare the interface: publicinterfaceExampleInterface{voiddoSomething();intgetSomething();} Abstract class An abstract class is a class that cannot be instantiated. It contains a mixture of abstract and non-abstract methods. Similar to interfaces, abstract methods in abstract classes are implemented by subclasses. However, abstract classes can also contain concrete methods, which provide default implementations. Declare abstract class: publicabstractcl

See all articles