Revisit ASP. WebAPI (second) advanced

Source: Internet
Author: User

Introduced

This article is of no reference value to the individual's review of Webapi.

The content of this article:

    1. Rest and Unitofwork
    2. Process for creating WEBAPI
    3. Use of ioc-unity
    4. MEF
    5. Custom URLs
    6. Base authentication and Token custom permissions
    7. Log Nlog
    8. Use of OData
    9. Owin self-hosted use

Code Address: Https://github.com/OtherRuan/Review-Serials

Some characteristics of WEBAPI

The WEBAPI provides several features:

1. Auto-Match HTTP method

GetMethod (), it is customary to directly match the Get HTTP method.

The Web API allows methods to have multiple types at the same time, such as:

[Acceptverbs ("Delete", "Get")]

Public Httpresponsemessage Multimethod ();

Multimethod can be used for delete, get two types of HTTP requests at the same time

2. The Web API also provides the ability to customize the route, such as defining its own parameters, as follows

[Route ("Data/{param1}/{param2}")]

public Object GetData (string param1, String param2) {}

Request Address: HTTP://LOCALHOST/DATA/1/2

The route attribute has the following 5 types to help you redefine your API routing

A) ActionName: Define the action name of your own route

b) HTTP method (Httpget,httppost,acceptverbs ...): Defines information about the type and version of your HTTP methods

c) Nonaction: Prevent the current action from being called

d) Route: Custom route, set parameters

e) Routeprefix: The prefix is defined on the controller, and all action routes under the controller will automatically

3. HttpClient, Httprequestmessage, Httpresponsemessage

Web Api under HTTPS

Https/ssl is the protocol that manages the transmission security of Internet message resources of computers. Let's introduce both.

Certificate: E-cert, an electronic signature that verifies the user, device, service, and corresponding private key by binding the public key

Certificate Authority (CA): The primary purpose is to specify which URLs are trusted URLs

Repository and unit of work

Repository Mode Benefits:

    1. Centralize data and Web service access logic
    2. Support Unit Testing
    3. Provides a flexible architecture to accommodate the expansion of the entire application design

Unit of work Duties:

    1. Management transactions
    2. Insert, delete, update operations for ordered data
    3. Prevention of duplicate updates.

The advantage of using the unit of work mode is that it allows you to focus more on business logic.

Create a WEBAPI project process
    1. Create Dal
    2. Create repository and unit of work
    3. Create entities
    4. Create Services
    5. Create Webapi
    6. Create IOC
    7. Using MEF to decouple dependent registration relationships
    8. Custom routes
    9. Create exception processing and logging capabilities
    10. Creating unit Tests

Questions:

    1. Context.entry (entity). state = entitystate.modified;
    2. IQueryable
    3. Unitofwork Inheritance IDisposable

Cause: He needs to release the link

    1. Dbentityvalidationexception e.entityvalidationerrors
    2. Gc. SuppressFinalize
Ioc–unity

Unity is a lightweight, extensible, dependency injection container that supports constructor injection, attribute injection, and method invocation injection.

Unity's Advantages:

    1. Provides simple object creation, especially hierarchical object structures and dependencies.
    2. Provide abstract requirements. Allows developers to specify dependencies at run time or in configuration.
    3. Increase flexibility and delay component configuration into containers
    4. It has a local service capability. Allows the user to save or cache the container. This applies specifically to ASP. Persistent session and application containers

To create a process:

    1. Installing Unity for MVC
    2. Create a Bootstrapper.cs file
      1. Initialise ()

Registration corresponds to reverse dependency

    1. Application_Start ()

Bootstrapper.initialise ();

2. Constructor injection

Private iemployeeservice _employeeservice;          Public Usercontroller (iemployeeservice employeeservice)        {            = employeeservice;        }
MEF (Managed extensibility Framework)

Although the previous IOC has previously reduced some of its dependencies, domain model still relies on the API.

The light-coupled architecture requires the following:

    1. Domain Model: Only associated with service layer
    2. Services: associated with rest terminal and domain model only
    3. REST API, the controller, is associated with the interface exposed by the IOC

To solve the API-dependent domain Model, we use MEF for decoupling.

The MEF (Managed extensibility Framework) is a library for creating scalable, lightweight applications. Application developers can use the library to discover and use extensions without having to configure them. Extension developers can also use the library to easily encapsulate code, avoiding the need to generate fragile hard dependencies. With MEF, you can reuse extensions not only within an application, but also between applications. (Excerpt from MSDN)

Process:

    1. Delete the registered configuration of the original container
      Container. Registertype<iemployeeservice, employeebusinesslayer>()                    . Registertype<UnitOfWork> (new Hierarchicallifetimemanager ());

2. Create a resolver class library

A. Adding UNITY.MVC

B. Adding a reference: System.ComponentModel.Composition

This DLL is part of the MEF and provides the core class of MEF

C. Adding an interface IComponent

Include method initialization method Setup, combined iregistercomponent

D. Adding an interface iregistercomponent

Methods for defining containers such as Registertype

E. Add the Componentloder load class.

Contains Loadcontainer, loads all modules with export properties and inherits IComponent in the DLL that specifies path path, and executes their setup method is the registration dependency.

varDircat =NewDirectorycatalog (path, pattern); varImportdef =buildimportdefinition (); Try            {                using(varAggregatecatalog =NewAggregatecatalog ())                    {AGGREGATECATALOG.CATALOGS.ADD (DIRCAT); using(varComponsitioncontainer =NewCompositioncontainer (Aggregatecatalog)) {                        varExports =componsitioncontainer.getexports (IMPORTDEF); varModules = exports. Select (export = Export. Value asIComponent). Where (M = = m! =NULL); varRegisterComponent =Newregistercomponent (container); foreach(varModuleinchmodules) {module.                        SetUp (registercomponent); }                    }                }

F. Each class library that needs to do the IOC, add Class Dependencyresolver, inherit IComponent, implement the Setup method, implement the Registertype function within the method, and achieve the role of dependency registration. Add Property Export

[Export (typeof(IComponent))]      Public class dependencyresolver:icomponent    {        publicvoid  SetUp (iregistercomponent registercomponent)        {            Registercomponent.registertype<iunitofwork, unitofwork>();        }    }

3. Modify the original configuration as follows:

" . \\bin " " Services.dll ");

Benefits of using MEF:

    1. Make applications more decoupled and extensible. Extension, you just need to add the new Dependencyresolver class in the same way, no dependencies.
    2. Dependency registration is automatically generated through reflection. You only need to specify the location of the corresponding DLL, as in the bin.
    3. When a database transaction or some modules do not want to be exposed to a service terminal, MEF becomes more secure and does not break the current design structure.
Overriding a custom URL using attributerouting

Process:

    1. In Webconfig's Register method, replace with Maphttpattributeroute (), as follows:
 Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//CONFIG. Routes.maphttproute (//Name: "Defaultapi",//routetemplate: "Api/{controller}/{id}",//defaults:new {id = routeparameter.optional}//);CONFIG.        Maphttpattributeroutes (); }    }

2. In Global.ascx, replace the original registration

protected void Application_Start ()        {            //webapiconfig.register (globalconfiguration.configuration);             globalconfiguration.configure (webapiconfig.register);}

3. Several route customization methods

A. Setting a prefix on a controller

[Routeprefix ("users/user")][routeprefix ("v1/users/ User")]

B. Custom route on action

[Route ("u/{id?} " )][route ("u/{id:range (1,3)}")][route ("U/id/{e:regex ( ^[0-9]$)}"][route ("~/myroute/users")]
Use Actionfilter to create WEBAPI-based authentication security and token-based custom permissions

Enterprise-class application security is especially important, especially when exposing our business data through services. Let's introduce the following:

    1. Authentication Certification

Authentication authentication is used to confirm the end user and verify that the user has access to the system. The Basic authentication technology will be adopted to understand how to implement authentication functionality in Webapi.

    1. Authorization authorization

Authorization authorization can be understood as completing the second part of the authentication certification to implement the security mechanism. Not all users who have access to the system can access all modules such as action. Authorization Specifies whether users can access specific system resources by setting roles and permissions to end users, or by providing secure tokens.

    1. Persistent session

RESTful services work in stateless protocols, such as HTTP. We can use token-based authorization technology to achieve the function of a persistent session. An authorized user that allows you to access resources within a certain amount of time and to re-instantiate requests for access by extending the session's effective time. Sites that use WEBAPI can persist sessions through the Basic authentication and token Base authorization.

Basic Authentication

Basic authentication is a mechanism. When a user requests a service, the user name password is nested in the request header. After the service receives the request, verifies that the certificate is valid, and then returns the response result. The response result for the invalid certificate is 401, which means no access.

Pros: Easy to implement, support all browsers, and become a restful standard certification.

Cons: User certificates are included in the request header and are vulnerable to attack. There is no persistence session, you cannot quit once a user logs in and sends a certificate multiple times to the service. And very vulnerable to attack, such as CSRF.

based on Token Authorized

Token is usually the encrypted key, and only the server or service knows what it means. When a user sends a request and passes tokens, the server determines whether the user has access to the system by token. The generated tokens can be stored in a database or configuration file. Tokens have their own life cycle, with expiry times.

Webapi use the Basic authentication and token authorization process:

    1. Create a user table
    2. Create service and Repository
    3. IOC
    4. Create Authorizationfilterattribute
      1. Implement Onauthrozation

I. Get user-related information genericidentity

filterContext.Request.Headers.Authorization.Scheme= ="Basic" Parameter.split (":") [0] Username, [1]password

Ii. invoking the service to obtain database user information for validation

5. By adding a property filter, or by adding a global filter at global

[Apiauthenticationfilter]globalconfiguration.configuration.filters.add (New Apiauthenticationfilter ());

Design flaws

Each request is sent with a user password. Suppose I create an app that authenticates only once when I log in. At this point I also have access to other services. Our application should be more secure, he must be able to bind a timely authenticated user, can not access the services not authorized to him.

Authorization is achieved through token. Only exposes services such as logins to the user. When the user logs in successfully, send a token (which can be either a GUID or an encrypted key) to the user, with the token on each request. In the persistence session, token has an expiration time, typically 15 minutes, and can be configured as a portal in Web. config. After the session expires, users log out and log back in to get a new token.

Using the action filter, Exception filter implements WEBAPI log fault tolerance function

NLog the Use

    1. NuGet Download Nlog
    2. Configure Nlog
      1. Configuration of the Configsection

2. Configuration of the Nlog node

3. Add the Apilog folder to the Web project

4. Add the Helpers folder and add the following files

      1. Nlogger class

The trace method that inherits Itracewriter, which is used primarily to log all types of errors and information.

5. Add Loggingfilterattribute inherit action Filter

Introducing the Nlogger class into

6. Register Loggingfilterattribute to Global

Error log

    1. Add Globalexceptionattribute class, inherit Exceptionfilterattribute, implement Onexception method

Inject the Nlogger

2. The rest of the operation is the same as log

Custom error Log

Errors can be categorized into three main categories: API-level errors, business errors, data errors

    1. Add Interface Iapiexception

Basic information property containing the property error

2. Add three classes of Apiexception, Apibusinessexception, apidataexception, Inherit iapiexception and exception

3. Referencing JSON serialization

Log needs to be able to serialize into JSON so that we can transfer the log objects to each module.

4. Modify the previous Nlogger class

5. Modify Globalexceptionattribute

6. In the controller, throw our custom error class

OData in the Webapi

OData is a protocol that provides the flexibility to create a queryable rest service, which, to be precise, provides a variety of query options, such as parameters, to determine the data that you specifically want to query. As the following link

Http://localhost/Products? $orderby =name

OData allows you to create queryable services, and when Terminal Services supports OData, you can filter the request results, such as extracting the first n data, sorting, selecting a piece of data, and so on.

Query options

ASP. NET WEBAPI supports the following types of:

    1. $orderby: Sorting
    2. $select: Select a column or an attribute
    3. $skip: Similar to LINQ, skips the first n data, extracts n+1 data
    4. $top: Top N
    5. $expand: Extending Entities
    6. $filter: Filter
    7. $inlinecount: Similar Paging

Use process

    1. NuGet Install OData
    2. The result set in the API refers to the method AsQueryable (), set to Queryable
_employeeservice.getall (). AsQueryable ()

3. Use of various query options

A. $top

/employee/all? $top =2

B. $filter

/employee/all?$ filter =name eq ' Ryan ' gets the data name equals Ryan

/employee/all?$ Filter =id LT 3 Gets the data with ID less than 3

C. $orderby

/employee/all?$ =name desc

D. $orderby and $top

/employee/all? $top =2&orderby = Name desc

E. $skip

/employee/all? $top =5$skip=2 The first 5 data of the 3rd article, 3-7

Filter the operator

eq

Equals

$filter =revenue EQ 100

Ne

Not equal to

$filter =revenue NE 100

Gt

Greater than

$filter =revenue GT 100

Ge

Greater than or equal

$filter =revenue GE 100

Lt

Less than

$filter =revenue LT 100

Le

Less than or equal

$filter =revenue le 100

and

And

$filter =revenue LT and Revenue GT 2000

Or

Or

$filter =contains (Name, ' (sample) ') or contains (name, ' Test ')

Not

does not contain

$filter =not contains (name, ' sample ')

( )

Parentheses field

(Contains (name, ' sample ') or contains (name, ' Test ')) and revenue GT 5000

Query function

Contains

$filter =contains (Name, ' (sample) ')

EndsWith

$filter =endswith (name, ' INC ')

StartsWith

$filter =startswith (name, ' a ')

F. Paging

Add Property [queryable (PageSize = 10)]

G. Setting the allowable options

[Queryable (Allowedqueryoptions =allowedqueryoptions.filter | Allowedqueryoptions.orderby)]

H. Allow a specific sort range

" ProductId ")]

I. Allowable operator range

[Queryable (allowedlogicaloperators = Allowedlogicaloperators.greaterthan)]

J. Allowable range of calculation operators

[Queryable (allowedarithmeticoperators = allowedarithmeticoperators.add)]
Create a self-hosted Webapi-owin
    1. Add Console App
    2. NuGet installation Webapi Owin self-host
    3. Add API
    4. Add Startup Class

Use Httpconfiguration to create a route and add it to the request pipeline by using the Appbuilder.usewebapi method

Use the startup class in the API project in the 5.Main function

6. Run the console

Reference documents

Http://www.codeproject.com/Articles/659131/Understanding-and-Implementing-ASPNET-WebAPI

Http://www.codeproject.com/Articles/838274/Web-API-Thoughts-of-Data-Streaming

http://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application#_Toc418969124

Http://www.codeproject.com/Articles/889242/WebAPI-Self-Hosting-Using-OWIN

Http://www.codeproject.com/Articles/631668/Learning-MVC-Part-Repository-Pattern-in-MVC-App

Http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in

Revisit ASP. WebAPI (second) advanced

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.