• ABP框架系列之十一:(AspNet-Core-ASPNET核心)


    Introduction

    This document describes ASP.NET Core integration for ASP.NET Boilerplate framework. ASP.NET Core integration is implemented in Abp.AspNetCore nuget package

    本文档介绍了ASP.NET样板ASP.NET核心集成框架。ASP.NET的核心集成在abp.aspnetcore NuGet包实现

    Migrating to ASP.NET Core?(迁移到ASP.NET Core

    If you have an existing project and considering to migrate to ASP.NET Core, you can read our blog post for our experince on the migration.

    如果你有一个现有的项目,考虑到ASP.NET的核心,你可以阅读我们的博客,我们在迁移中的经验。

    Startup Template(启动模板

    You can create your project from startup template, which is a simple, empty web project but properly integrated and configured to work with ABP framework.

    您可以从启动模板创建项目,这是一个简单的、空的Web项目,但经过适当的集成和配置,可以与ABP框架一起工作。

    Configuration

    Startup Class

    To integrate ABP to ASP.NET Core, we should make some changes in the Startup class as shown below:

    public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //...
    
            //Configure Abp and Dependency Injection. Should be called last.
            return services.AddAbp<MyProjectWebModule>(options =>
            {
                //Configure Log4Net logging (optional)
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseLog4Net().WithConfig("log4net.config")
                );
            });
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Initializes ABP framework and all modules. Should be called first.
            app.UseAbp(); 
            
            //...
        }
    }

    Module Configuration(模块配置

    You can use startup configuration to configure AspNet Core Module (using Configuration.Modules.AbpAspNetCore() in PreInitialize of your module).

    你可以使用启动配置配置ASPNET核心模块(使用配置模块。abpaspnetcore()在分发你的模块)。

    Controllers

    Controllers can be any type of classes in ASP.NET Core. It's not restricted to classes derived from Controller class. By default, a class ends with Controller (like ProductController) is considered as MVC Controller. You can also add MVC's [Controller] attribute to any class to make it a controller. This is the way ASP.NET Core MVC is working. See ASP.NET Core documentation for more.

    If you will use web layer classes (like HttpContext) or return a view, it's better to inherit from AbpController (which is derived from MVC's Controller) class. But if you are creating an API controller just works with objects, you can consider to create a POCO controller class or you can use your application services as controllers as described below.

    控制器可以在ASP.NET核心的任何类型的类。它不限于从控制器类派生的类。默认情况下,一类以控制器(如ProductController)作为MVC控制器。您还可以向任何类添加MVC的[控制器]属性,使之成为控制器。这是ASP.NET核心的MVC工作。更多的看到ASP.NET的核心文件。

    如果你会使用Web层类(如HttpContext)或返回一个视图,这是更好地继承abpcontroller(这是从MVC的控制器)类。但是如果你正在创建一个API控制器只是工作的对象,你可以考虑创建一个POCO控制器类或您可以使用您的应用程序服务作为控制器,如下所述。

    Application Services as Controllers

    ASP.NET Boilerplate provides infrastructure to create application services. If you want to expose your application services to remote clients as controllers (as previously done using dynamic web api), you can easily do it by a simple configuration in PreInitialize method of your module. Example:

    ASP.NET样板提供基础设施创建应用程序服务。如果你想让你的应用服务远程客户作为控制器(如先前使用动态Web API),你可以很容易做到的一个简单的配置分发你的模块的方法。例子:

    Configuration.Modules.AbpAspNetCore().CreateControllersForAppServices(typeof(MyApplicationModule).Assembly, moduleName: 'app', useConventionalHttpVerbs: true);

    CreateControllersForAppServices method gets an assembly and converts all application services to MVC controllers in that assembly. You can use RemoteService attribute to enable/disable it for method or class level.

    createcontrollersforappservices方法获取一个组件,将所有的应用服务在MVC控制器组件。你可以使用RemoteService属性来启用/禁用它的类或方法的水平。

    When an application service is converted to MVC Controller, it's default route will be like /api/services/<module-name>/<service-name>/<method-name>. Example: If ProductAppService defines a Create method, it's URL will be/api/services/app/product/create (assumed that module name is 'app').

    当应用程序服务被转换为MVC控制器时,它的默认路由将类似于/api/services/<module-name>/<service-name>/<method-name>。例如:如果productappservice定义一个创建方法,它的URL将/api/services/app/product/create/创建(假设模块的名称是“app”)。

    If useConventionalHttpVerbs set to true (which is the default value), then HTTP verbs for service methods are determined by naming conventions:

    如果useconventionalhttpverbs设置为true(这是默认值),然后通过命名约定确定HTTP动词使用方法:

    • Get: Used if method name starts with 'Get'.
    • Put: Used if method name starts with 'Put' or 'Update'.
    • Delete: Used if method name starts with 'Delete' or 'Remove'.
    • Post: Used if method name starts with 'Post', 'Create' or 'Insert'.
    • Patch: Used if method name starts with 'Patch'.
    • Otherwise, Post is used as default HTTP verb.

    You can use any ASP.NET Core attributes to change HTTP methods or routes of the actions (but surely, this requires to add reference to related ASP.NET Core package).

    Note: Previously, dynamic web api system was requiring to create service interfaces for application services. But this is not required for ASP.NET Core integration. Also, MVC attributes should be added to the service classes, even you have interfaces.

    你可以使用任何ASP.NET的核心属性改变HTTP方法或路由的行为(当然,这需要添加参考相关ASP.NET核心包)。

    注意:以前,动态Web API系统要求为应用程序服务创建服务接口。但这并不是ASP.NET的核心集成所需。另外,MVC属性应该添加到服务类中,即使您有接口。

    Filters

    ABP defines some pre-built filters for AspNet Core. All of them are added to all actions of all controllers by default.

    ABP定义了预建的过滤器ASPNET核心。所有这些都默认添加到所有控制器的所有操作中。

    Authorization Filter(授权过滤

    AbpAuthorizationFilter is used to integrate to authorization system and feature system.

    abpauthorizationfilter是用来整合授权系统和特征系统。

    • You can define AbpMvcAuthorize attribute for actions or controllers to check desired permissions before action execution.
    • You can define RequiresFeature attribute for actions or controllers to check desired features before action execution.
    • You can define AllowAnonymous (or AbpAllowAnonymous in application layer) attribute for actions or controllers to suppress authentication/authorization.
    • 你可以定义为行动或控制器在执行检查所需的权限abpmvcauthorize属性。
      你可以定义为行动或控制器在执行检查所需的功能requiresfeature属性。
      你可以定义allowanonymous(或abpallowanonymous在应用层)的行动或控制器来抑制认证/授权属性。

    Audit Action Filter(审计行为过滤

    AbpAuditActionFilter is used to integrate to audit logging system. It logs all requests to all actions by default (if auditing is not disabled). You can control audit logging using Audited and DisableAuditing attributes for actions and controllers.

    abpauditactionfilter是用来整合审计日志系统。默认情况下,它将所有请求记录到所有操作(如果没有禁用审核)。你可以控制审计日志审计和disableauditing使用动作和控制器属性。

    Validation Action Filter(动作验证过滤器

    AbpValidationActionFilter is used to integrate to validation system and automatically validate all inputs of all actions. In addition to ABP's built-in validation & normalization, it also checks MVC's Model.IsValid property and throws validation exception if action inputs have any invalid value.

    You can control validation using EnableValidation and DisableValidation attributes for actions and controllers.

    abpvalidationactionfilter用于集成验证系统和自动验证所有输入的所有行动。此外,ABP的内置验证和标准化,它还检查model.isvalid财产将MVC的验证异常如果有任何动作输入的值无效。

    你可以控制使用动作和控制器enablevalidation和disablevalidation属性验证。

    Unit of Work Action Filter(工作单元动作过滤

    AbpUowActionFilter is used to integrate to Unit of Work system. It automatically begins a new unit of work before an action execution and completes unit of work after action exucition (if no exception is thrown).

    You can use UnitOfWork attribute to control behaviour of UOW for an action. You can also use startup configuration to change default unit of work attribute for all actions.

    abpuowactionfilter是用来整合的工作系统。它会自动开始一个新的工作单位前一个动作的执行和完成行动后exucition工作单位(如果没有抛出异常)。

    你可以使用属性来控制一个动作UnitOfWork UOW的行为。
    还可以使用启动配置更改所有操作的默认工作单元属性。

    Exception Filter(异常过滤

    AbpExceptionFilter is used to handle exceptions thrown from controller actions. It handles and logs exceptions and returns wrapped response to the client.

    • It only handles object results, not view results. So, actions returns any object, JsonResult or ObjectResult will be handled. Action returns a view or any other result type implements IActionsResult are not handled. It's suggested to use built-in UseExceptionHandler extension method defined in Microsoft.AspNetCore.Diagonistics package to handle view exceptions.
    • Exception handling and logging behaviour can be changed using WrapResult and DontWrapResult attributes for methods and classes.
    • abpexceptionfilter是用来处理从控制器动作抛出的异常。它处理和记录异常并返回对客户机的包装响应。

      它只处理对象结果,而不查看结果。所以,行动返回任何对象,objectresult JsonResult或将处理。动作返回一个视图或任何其他结果类型实现了iactionsresult处理不。建议使用内置的useexceptionhandler扩展方法在microsoft.aspnetcore.diagonistics包定义视图的例外处理。
      异常处理和日志记录行为可以使用方法和类wrapresult和dontwrapresult属性改变。

    Result Filter(结果过滤

    AbpResultFilter is mainly used to wrap result action if action is successfully executed.

    • It only wraps results for JsonResult, ObjectResult and any object which does not implement IActionResult (and also their async versions). If your action is returning a view or any other type of result, it's not wrapped.
    • WrapResult and DontWrapResult attributes can be used for methods and classes to enable/disable wrapping.
    • You can use startup configuration to change default behaviour for result wrapping.
    • abpresultfilter主要用于包装的行动,如果行动是成功执行的结果。

      这只包的结果objectresult JsonResult,任何对象没有实现iactionresult(也是他们的异步版本)。如果您的操作返回视图或其他类型的结果,则不会包装。
      wrapresult和dontwrapresult属性可用于启用/禁用的包装方法和类。
      可以使用启动配置更改结果包装的默认行为。

    Result Caching For Ajax Requests(用于Ajax请求的结果缓存

    AbpResultFilter adds Cache-Control header (no-cache, no-store...) to the response for AJAX Requests. Thus, it prevents browser caching of AJAX responses even for GET requests. This behaviour can be disabled by the configuration or attributes. You can use NoClientCache attrbiute to prevent caching (default) or AllowClientCache attrbiute to allow browser to cache results. Alternatively you can implement IClientCacheAttribute to create your special attribute for finer control.

    abpresultfilter添加缓存控制头(没有缓存,没有存储…)的响应Ajax请求。因此,即使GET请求,它也阻止浏览器缓存Ajax响应。可以通过配置或属性禁用此行为。你可以使用noclientcache attrbiute防止缓存(默认)或allowclientcache attrbiute让浏览器缓存结果。或者你可以实现iclientcacheattribute为更好的控制创建您的特殊属性。

    Model Binders(模型绑定

    AbpDateTimeModelBinder is used to normalize DateTime (and Nullable<DateTime>) inputs using Clock.Normalize method.

    abpdatetimemodelbinder用来规范datetime(and Nullable<DateTime>)投入使用的时钟规范方法。

    Views

    MVC Views can be inherited from AbpRazorPage to automatically inject most used infrastructure (LocalizationManager, PermissionChecker, SettingManager... etc.). It also has shortcut methods (like L(...) for localize texts). Startup template inherits it by default.

    You can inherit your web components from AbpViewComponent instead of ViewComponent to take advantage of base properties and methods.

    MVC视图可以继承从AbpRazorPage到自动注入最常用的基础(localizationmanager,PermissionChecker,settingmanager…等)。它也有快捷方法(如本地化文本的L(…))。启动模板默认继承它。

    你可以继承您的Web部件代替ViewComponent abpviewcomponent利用基地的属性和方法。

    Client Proxies(客户端代理

    ABP can automatically create javascript proxies for all MVC Controllers (not only application services). It's created for Application Services as Controllers (see the section above) by default. You can add [RemoteService] attribute to any MVC controller to create client proxy for it. Javascript proxies are dynamically generated on runtime. You need to add given script definition to your page:

    ABP可以为所有MVC控制器(不仅仅是应用程序服务)自动创建JavaScript代理。它是为应用程序服务创建的,默认情况下是控制器(参见以上部分)。您可以添加【RemoteService ]属性的任何MVC控制器为它创建客户端代理。JavaScript代理是在运行时动态生成的。您需要将给定的脚本定义添加到页面中:

    <script src="~/AbpServiceProxies/GetAll?type=jquery" type="text/javascript"></script>

    Currently, only JQuery proxies are generated. We can then call an MVC method with javascript as shown below:

    目前只生成jQuery代理。然后,我们可以调用JavaScript的MVC方法,如下所示:

    abp.services.app.product.create({
        name: 'My test product',
        price: 99
    }).done(function(result){
        //...
    });

    Integration Testing(集成测试

    Integration testing is fairly easy for ASP.NET Core and it's documented it's own web site in details. ABP follows this guide and provides AbpAspNetCoreIntegratedTestBase class in Abp.AspNetCore.TestBase package. It makes integration testing even easier.

    It's better to start by investigating integration tests in startup template to see it in action.

    集成测试是相当容易的,这是ASP.NET核心的细节记录在自己的网站。公司遵循本指南和abp.aspnetcore.testbase包提供了abpaspnetcoreintegratedtestbase类。它使集成测试更加容易。

    最好先调查启动模板中的集成测试,看看它是否生效。

  • 相关阅读:
    vue与自定义元素的关系
    vue用组件构建应用
    vue处理用户输入
    vue条件与循环
    vue声明式渲染
    Java编程的逻辑 (86)
    Java编程的逻辑 (85)
    Java编程的逻辑 (84)
    Java编程的逻辑 (83)
    Java编程的逻辑 (82)
  • 原文地址:https://www.cnblogs.com/smileberry/p/7909951.html
Copyright © 2020-2023  润新知