[译]用于企业应用程序的Angular2和WebApi(SPA)-第6部分-RESTful和WebApi
By robot-v1.0
本文链接 https://www.kyfws.com/applications/angular-webapi-spa-for-enterprise-app-part-restful-zh/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 6 分钟阅读 - 2773 个词 阅读量 0[译]用于企业应用程序的Angular2和WebApi(SPA)-第6部分-RESTful和WebApi
原文地址:https://www.codeproject.com/Articles/1151586/Angular-WebApi-SPA-for-Enterprise-App-Part-RESTful
原文作者:tranthanhtu.vn
译文由本站 robot-v1.0 翻译
前言
In this article, We will have a look to unserstand how RESTful/WebApi was applied in my code
在本文中,我们将了解一下如何在我的代码中应用RESTful/Web Api
系列中的其他文章(Other Articles in the Series)
- 总览(Overview)
- 新增权限(Add new Permission)
- 项目结构(Project structure)
- 多国语言(i18n)(Multi-Languages (i18n))
- DI&IoC-为什么和为什么不?(DI & IoC - Why and Why not?)
- RESTful和Web Api(RESTful & WebApi)
- 管理应用程序生命周期(Manage Application Lifecycle)
- 构建和部署应用程序(Build & Deploy Application)
- 带有Angular 2的TinyERP的新版本(打字稿)(New version of TinyERP with Angular 2 (typescript))
- CQRS:避免企业应用程序中的性能问题(基本)(CQRS: Avoiding performance issues in enterprise app (basic))
- 多个数据存储:扩展存储库(第1部分)(Multiple data-stores: Scale your repository (Part 1))
- 多个数据存储:扩展存储库(第2部分)(Multiple data-stores: Scale your repository (Part 2))
介绍(Introduction)
在我的代码中,我们使用angular2(打字稿)处理客户端逻辑,并在服务器端(c#)执行业务逻辑.(In my code, we use angular2 (typescript) handles client logic and performs business logic on server side (c#).)
客户端通过Web Api中编写的RESTful Web服务与服务器端进行通信.(The client communicates with server side through RESTful web service written in WepApi.)
如何获取代码(How to Get the Code)
请在以下位置检查代码(Please check out the code at) https://github.com/techcoaching/TinyERP(https://github.com/techcoaching/TinyERP) .(.)
致电客户(Calling from Client)
在页面中,我们调用适当的服务:(In the page, we call to appropriated service:)
@Component({
selector: "roles",
templateUrl: "app/modules/security/permission/permissions.html",
directives: [Grid, PageActions, Page]
})
export class Permissions extends BasePage {
private router: Router;
public model: PermissionsModel;
constructor(router: Router) {
super();
let self: Permissions = this;
self.router = router;
self.model = new PermissionsModel(self.i18nHelper);
self.loadPermissions();
this.model.addPageAction(new PageAction("btnAddPer", "security.permissions.addPermissionAction", () => self.onAddNewPermissionClicked()));
}
private loadPermissions() {
let self: Permissions = this;
permissionService.getPermissions().then(function (items: Array<any>) {
self.model.importPermissions(items);
});
}
}
在permissionService中,它实际上是使用IConnector(IConnector,以便从angular依次使用Http)并将请求发送到服务器端.(In permissionService, it was actually use the IConnector (IConnector in order using Http from angular) and send request to server side.)
import configHelper from "../../../../common/helpers/configHelper";
import {Promise} from "../../../../common/models/promise";
import {IoCNames} from "../../../../common/enum";
import {IConnector} from "../../../../common/connectors/iconnector";
let permissionService = {
getPermissions: getPermissions
};
export default permissionService;
function getPermissions(): Promise {
let connector: IConnector = window.ioc.resolve(IoCNames.IConnector);
let url = String.format("{0}permissions", configHelper.getAppConfig().api.baseUrl);
return connector.get(url);
}
在IConnector中,我们使用Http服务:(In IConnector, we use Http service:)
export class RESTConnector implements IConnector {
private static http: Http;
private static eventManager: EventManager;
constructor() {
let http: Http = window.appState.getInjector().get(Http);
this.setHttp(http);
}
public get(url: string): Promise {
RESTConnector.eventManager.publish(LoadingIndicatorEvent.Show);
let def = PromiseFactory.create();
let headers = new JsonHeaders();
RESTConnector.http.get(url, { headers: headers })
.map((response: any) => response.json())
.subscribe(
(data: any) => this.handleResponse(def, data),
(exception: any) => this.handleException(def, exception)
);
return def;
}
}
API处理(服务器端)(Handling on API (Server side))
我们有控制器,我们收到了请求:(We have the controller, we receive the request:)
隐藏(Hide)收缩(Shrink)
复制代码(Copy Code)```
namespace App.Api.Features.Security
{
[RoutePrefix(“api/permissions”)]
public class PermissionsController : ApiController
{
[HttpGet]
[Route()]
public IResponseData<IList> GetPermissions()
{
IResponseData<IList> response = new ResponseData<IList>();
try
{
IPermissionService permissionService = IoC.Container.Resolve();
IList pers = permissionService.GetPermissions();
response.SetData(pers);
}
catch (ValidationException ex)
{
response.SetErrors(ex.Errors);
response.SetStatus(System.Net.HttpStatusCode.PreconditionFailed);
}
return response;
}
}
}
如果我们将参数与请求一起发送到服务器.它们应映射到DTO(数据传输对象).(*If we have parameters sent to server along with request. they should be mapped to DTO (Data Transfer Object).*)
在RESTful中,我们知道应该对指定的操作(获取,创建,更新,删除)和适当的URI使用哪个Http Verb.因此,我认为我们不再在这里讨论.(*In RESTful, we know which Http Verb should be used for specified action (Get, Create, Update, Delete) and appropriated URI. So I think we will not discuss here again.*)
有一些不同,我只想澄清一下:(*There are some different, I just want to clarify:*)
错误/异常有两种类型,我们返回给客户端:基础架构错误和业务错误(*There are 2 types of errors/ exception, we returned to client: Infrastructure Error and Business Error*)
#### 基础架构错误(*Infrastructure Error*)
我们将其用于与网络有关的一些错误(未找到,超时,..),IIS上的配置.这意味着我们的业务代码未执行.(*we use this for some errors related to network (not found, time out, ....), configuration on IIS. it means our business code was not executed.*)
#### 业务错误(*Business Error*)
在这种情况下,从客户端发送的用于执行特定业务逻辑的数据无效.(*we use this for the case, data was sent from clien for doing specified business logic is invalid.*)
如:用户名或密码不匹配.对于这种情况,我们不应该返回500 HttpCode,因为客户端可能不了解服务器端发生了什么.(*Such as: user name or pwd does not match. For this case, we should not return 500 HttpCode, as client may not understand what was happended on server side.*)
因此,我们需要将错误的代码返回给客户端.(*So we need to return the client side the code for that error.*)
隐藏(*Hide*)复制代码(*Copy Code*)```
IResponseData<IList<PermissionAsKeyNamePair>> response = new ResponseData<IList<PermissionAsKeyNamePair>>();
try
{
}
catch (ValidationException ex)
{
response.SetErrors(ex.Errors);
response.SetStatus(System.Net.HttpStatusCode.PreconditionFailed);
}
return response;
REST客户端的输出如下:(The output from REST client as below:)
我们可以看到,在API上可以将多个无效验证发送回客户端.(We can see, on the API can send multiple invalid validation back to client.)
在客户端上,我们可以在UI上显示它们.而不是常见错误消息,如下图所示:(On the client we can show them on the UI. rather than common error message as photo below:)
在适当的服务中,我们验证请求并在无效时抛出异常,如下所示:(In the appropriated service, we validate the request and throw exception if invalid like this:)
隐藏(Hide)复制代码(Copy Code)``` private void ValidateUserLoginRequest(UserSignInRequest request) { ValidationException exception = new ValidationException(); if (request == null) { exception.Add(new ValidationError(“common.invalidRequest”)); } if (String.IsNullOrWhiteSpace(request.Email)) { exception.Add(new ValidationError(“registration.signin.validation.emailRequired”)); } if (String.IsNullOrWhiteSpace(request.Pwd)) { exception.Add(new ValidationError(“registration.signin.validation.pwdRequired”)); } IUserRepository userRepository = IoC.Container.Resolve(); User userProfile = userRepository.GetByEmail(request.Email);
if (userProfile == null || EncodeHelper.EncodePassword(request.Pwd) != userProfile.Password)
{
exception.Add(new ValidationError("registration.signin.validation.invalidEmailOrPwd"));
}
exception.ThrowIfError();
}
## 概要(*Summary*)
在某些情况下,来自API成功的响应(状态码200),但是我们有业务逻辑异常.(*In some case, the response from the API success (status code 200) but we have the business logic exception.*)
我的一些朋友告诉我,这可能会使您感到困惑.(*Some of my friends told me that this may a little confuse.*)
如果您还有其他更好的解决方案,请告诉我.我很感激(*If you have other better solution, Please let me know. I appriciate*)
有关更多信息:(*For more information about:*)
- Angular2,用于:(*Angular2, For:*)
- 有关Angular的概述,请访问(*An overview about Angular, please visit*) [https://www.codeproject.com/Articles/1164843/Angular-Overview(*https://www.codeproject.com/Articles/1164843/Angular-Overview*)](https://www.codeproject.com/Articles/1164843/Angular-Overview)
- 在Angular中进行路由,请访问(*Routing in Angular, please visit*) [https://www.codeproject.com/Articles/1164813/Angular-Routing(*https://www.codeproject.com/Articles/1164813/Angular-Routing*)](https://www.codeproject.com/Articles/1164813/Angular-Routing)
- Angular中的组件,请访问(*Component in Angular, please visit*) [https://www.codeproject.com/Articles/1166112/Angular-Component(*https://www.codeproject.com/Articles/1166112/Angular-Component*)](https://www.codeproject.com/Articles/1166112/Angular-Component)
- 在Angular中绑定,请访问(*Binding in Angular, please visit*) [https://www.codeproject.com/Articles/1166418/Angular-Binding(*https://www.codeproject.com/Articles/1166418/Angular-Binding*)](https://www.codeproject.com/Articles/1166418/Angular-Binding)
- Angular指令,请访问(*Directive in Angular, Please visit*)
- 第1部分:(*Part 1:*) [https://www.codeproject.com/Articles/1168139/Angular-Directives(*https://www.codeproject.com/Articles/1168139/Angular-Directives*)](https://www.codeproject.com/Articles/1168139/Angular-Directives)
- 第2部分:(*Part 2:*) [https://www.codeproject.com/Articles/1168995/Angular-Directives-Part(*https://www.codeproject.com/Articles/1168995/Angular-Directives-Part*)](https://www.codeproject.com/Articles/1168995/Angular-Directives-Part)
- [将" Angular 2"功能追加到当前的" Angular 1"应用程序中(*Append "Angular 2" feature into current "Angular 1" application*)](https://www.codeproject.com/Articles/1173568/Append-Angular-Feature-into-Angular-Application)
- 休息:(*REST:*)
- 有关概述的概念,请访问(*For overview concept, please visit*) [https://www.codeproject.com/Articles/1164842/REST-概述(*https://www.codeproject.com/Articles/1164842/REST-Overview*)](https://www.codeproject.com/Articles/1164842/REST-Overview)
- 要在Web API(C#)中使用REST,请访问(*For using REST in WebAPI (C#), please visit*) [https://www.codeproject.com/Articles/1168872/REST-in-WebApi(*https://www.codeproject.com/Articles/1168872/REST-in-WebApi*)](https://www.codeproject.com/Articles/1168872/REST-in-WebApi)
## 许可
本文以及所有相关的源代码和文件均已获得[The Code Project Open License (CPOL)](http://www.codeproject.com/info/cpol10.aspx)的许可。
Javascript
XML
C#
.NET
IIS
Visual-Studio
ASP.NET
DBA
Dev
Architect
新闻
翻译