@ -1,5 +1,6 @@
|
||||
{
|
||||
"culture": "en",
|
||||
"texts": {
|
||||
"Buy": "Buy"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
{
|
||||
"culture": "hu",
|
||||
"texts": {
|
||||
"FAQ": "GYIK"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,690 @@
|
||||
# How to Design Multi-Lingual Entity
|
||||
|
||||
## Introduction
|
||||
|
||||
If you want to open up to the global market these days, end-to-end localization is a must. ABP provides an already established infrastructure for static texts. However, this may not be sufficient for many applications. You may need to fully customize your app for a particular language and region.
|
||||
|
||||
Let's take a look at a few quotes from Christian Arno's article "[How Foreign-Language Internet Strategies Boost Sales](https://www.mediapost.com/publications/article/155250/how-foreign-language-internet-strategies-boost-sal.html)" to better understand the impact of this:
|
||||
|
||||
- 82% of European consumers are less likely to buy online if the site is not in their native tongue ([Eurobarometer survey](http://europa.eu/rapid/pressReleasesAction.do?reference=IP/11/556)).
|
||||
- 72.4% of global consumers are more likely to buy a product if the information is available in their own language ([Common Sense Advisory](http://www.commonsenseadvisory.com/)).
|
||||
- The English language currently only accounts for 31% of all online use, and more than half of all searches are in languages other than English.
|
||||
- Today, 42% of all Internet users are in Asia, while almost one-quarter are in Europe and just over 10% are in Latin America.
|
||||
|
||||
- Foreign languages have experienced exponential growth in online usage in the past decade -- with Chinese now officially the [second-most-prominent-language](http://english.peopledaily.com.cn/90001/90776/90882/7438489.html) on the Web. [Arabic](http://www.internetworldstats.com/stats7.htm) has increased by a whopping 2500%, while English has only risen by 204%
|
||||
|
||||
If you are looking for ways to expand your market share by fully customizing your application for a particular language and region, in this article I will explain how you can do it with ABP framework.
|
||||
|
||||
### Source Code
|
||||
|
||||
You can find the source code of the application at [abpframework/abp-samples](https://github.com/abpframework/abp-samples/tree/master/AcmeBookStoreMultiLingual).
|
||||
|
||||
### Demo of the Final Application
|
||||
|
||||
At the end of this article, we will have created an application same as in the gif below.
|
||||
|
||||

|
||||
|
||||
## Development
|
||||
|
||||
In order to keep the article short and get rid of unrelated information in the article (like defining entities etc.), we'll be using the [BookStore](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore) example, which is used in the "[Web Application Development Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=MVC&DB=EF)" documentation of ABP Framework and we will make the Book entity as multi-lingual. If you do not want to finish this tutorial, you can find the application [here](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore).
|
||||
|
||||
### Determining the data model
|
||||
|
||||
We need a robust, maintainable, and efficient data model to store content in multiple languages.
|
||||
|
||||
> I read many articles to determine the data model correctly, and as a result, I decided to use one of the many approaches that suit us.
|
||||
> However, as in everything, there is a trade-off here. If you are wondering about the advantages and disadvantages of the model we will implement compared to other models, I recommend you to read [this article](https://vertabelo.com/blog/data-modeling-for-multiple-languages-how-to-design-a-localization-ready-system/).
|
||||
|
||||

|
||||
|
||||
As a result of the tutorial, we already have the `Book` and `Author` entities, as an extra, we will just add the `BookTranslation`.
|
||||
|
||||
> In the article, we will make the Name property of the Book entity multi-lingual, but the article is independent of the Book entity, you can make the entity you want multi-lingual with similar codes according to your requirements.
|
||||
|
||||
#### Acme.BookStore.Domain.Shared
|
||||
|
||||
Create a folder named `MultiLingualObjects` and create the following interfaces in its contents.
|
||||
|
||||
We will use the `IObjectTranslation` interface to mark the translation of a multi-lingual entity:
|
||||
|
||||
```csharp
|
||||
public interface IObjectTranslation
|
||||
{
|
||||
string Language { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
We will use the `IMultiLingualObject<TTranslation>` interface to mark multi-lingual entities:
|
||||
|
||||
```csharp
|
||||
public interface IMultiLingualObject<TTranslation>
|
||||
where TTranslation : class, IObjectTranslation
|
||||
{
|
||||
ICollection<TTranslation> Translations { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
#### Acme.BookStore.Domain
|
||||
|
||||
In the `Books` folder, create the `BookTranslation` class as follows:
|
||||
|
||||
```csharp
|
||||
public class BookTranslation : Entity, IObjectTranslation
|
||||
{
|
||||
public Guid BookId { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
public string Language { get; set; }
|
||||
|
||||
public override object[] GetKeys()
|
||||
{
|
||||
return new object[] {BookId, Language};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`BookTranslation` contains the `Language` property, which contains a language code for translation and a reference to the multi-lingual entity. We also have the `BookId` foreign key to help us know which book is translated.
|
||||
|
||||
Implement `IMultiLingualObject` in the `Book` class as follows:
|
||||
|
||||
```csharp
|
||||
public class Book : AuditedAggregateRoot<Guid>, IMultiLingualObject<BookTranslation>
|
||||
{
|
||||
public Guid AuthorId { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
public BookType Type { get; set; }
|
||||
|
||||
public DateTime PublishDate { get; set; }
|
||||
|
||||
public float Price { get; set; }
|
||||
|
||||
public ICollection<BookTranslation> Translations { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
Create a folder named `MultiLingualObjects` and add the following class inside of this folder:
|
||||
|
||||
```csharp
|
||||
public class MultiLingualObjectManager : ITransientDependency
|
||||
{
|
||||
protected const int MaxCultureFallbackDepth = 5;
|
||||
|
||||
public async Task<TTranslation> FindTranslationAsync<TMultiLingual, TTranslation>(
|
||||
TMultiLingual multiLingual,
|
||||
string culture = null,
|
||||
bool fallbackToParentCultures = true)
|
||||
where TMultiLingual : IMultiLingualObject<TTranslation>
|
||||
where TTranslation : class, IObjectTranslation
|
||||
{
|
||||
culture ??= CultureInfo.CurrentUICulture.Name;
|
||||
|
||||
if (multiLingual.Translations.IsNullOrEmpty())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var translation = multiLingual.Translations.FirstOrDefault(pt => pt.Language == culture);
|
||||
if (translation != null)
|
||||
{
|
||||
return translation;
|
||||
}
|
||||
|
||||
if (fallbackToParentCultures)
|
||||
{
|
||||
translation = GetTranslationBasedOnCulturalRecursive(
|
||||
CultureInfo.CurrentUICulture.Parent,
|
||||
multiLingual.Translations,
|
||||
0
|
||||
);
|
||||
|
||||
if (translation != null)
|
||||
{
|
||||
return translation;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected TTranslation GetTranslationBasedOnCulturalRecursive<TTranslation>(
|
||||
CultureInfo culture, ICollection<TTranslation> translations, int currentDepth)
|
||||
where TTranslation : class, IObjectTranslation
|
||||
{
|
||||
if (culture == null ||
|
||||
culture.Name.IsNullOrWhiteSpace() ||
|
||||
translations.IsNullOrEmpty() ||
|
||||
currentDepth > MaxCultureFallbackDepth)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var translation = translations.FirstOrDefault(pt => pt.Language.Equals(culture.Name, StringComparison.OrdinalIgnoreCase));
|
||||
return translation ?? GetTranslationBasedOnCulturalRecursive(culture.Parent, translations, currentDepth + 1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With `MultiLingualObjectManager`'s `FindTranslationAsync` method, we get the translated version of the book according to `CurrentUICulture`. If no translation of culture is found, we return null.
|
||||
|
||||
> Every thread in .NET has `CurrentCulture` and `CurrentUICulture` objects.
|
||||
|
||||
#### Acme.BookStore.EntityFrameworkCore
|
||||
|
||||
In the `OnModelCreating` method of the `BookStoreDbContext` class, configure the `BookTranslation` as follows:
|
||||
|
||||
```csharp
|
||||
builder.Entity<BookTranslation>(b =>
|
||||
{
|
||||
b.ToTable(BookStoreConsts.DbTablePrefix + "BookTranslations",
|
||||
BookStoreConsts.DbSchema);
|
||||
|
||||
b.ConfigureByConvention();
|
||||
|
||||
b.HasKey(x => new {x.BookId, x.Language});
|
||||
});
|
||||
```
|
||||
|
||||
> I haven't explicitly set up a one-to-many relationship between `Book` and `BookTranslation` here, but the entity framework will do it for us.
|
||||
|
||||
After that, you can just run the following command in a command-line terminal to add a new database migration (in the directory of the `EntityFrameworkCore` project):
|
||||
|
||||
```bash
|
||||
dotnet ef migrations add Added_BookTranslation
|
||||
```
|
||||
|
||||
This will add a new migration class to your project. You can then run the following command (or run the `.DbMigrator` application) to apply changes to the database:
|
||||
|
||||
```bash
|
||||
dotnet ef database update
|
||||
```
|
||||
|
||||
Add the following code to the `ConfigureServices` method of the `BookStoreEntityFrameworkCoreModule`:
|
||||
|
||||
```csharp
|
||||
Configure<AbpEntityOptions>(options =>
|
||||
{
|
||||
options.Entity<Book>(bookOptions =>
|
||||
{
|
||||
bookOptions.DefaultWithDetailsFunc = query => query.Include(o => o.Translations);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Now we can use `WithDetailsAsync` without any parameters on `BookAppService` knowing that `Translations` will be included.
|
||||
|
||||
#### Acme.BookStore.Application.Contracts
|
||||
|
||||
Implement `IObjectTranslation` in the `BookDto` class as follows:
|
||||
|
||||
```csharp
|
||||
public class BookDto : AuditedEntityDto<Guid>, IObjectTranslation
|
||||
{
|
||||
public Guid AuthorId { get; set; }
|
||||
|
||||
public string AuthorName { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
public BookType Type { get; set; }
|
||||
|
||||
public DateTime PublishDate { get; set; }
|
||||
|
||||
public float Price { get; set; }
|
||||
|
||||
public string Language { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
`Language` property is required to understand which language the translated book name belongs to in the UI.
|
||||
|
||||
Create the `AddBookTranslationDto` class in the `Books` folder as follows:
|
||||
|
||||
```csharp
|
||||
public class AddBookTranslationDto : IObjectTranslation
|
||||
{
|
||||
[Required]
|
||||
public string Language { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
Add the `AddTranslationsAsync` method to the `IBookAppService` as follows:
|
||||
|
||||
```csharp
|
||||
public interface IBookAppService :
|
||||
ICrudAppService<
|
||||
BookDto,
|
||||
Guid,
|
||||
PagedAndSortedResultRequestDto,
|
||||
CreateUpdateBookDto>
|
||||
{
|
||||
Task<ListResultDto<AuthorLookupDto>> GetAuthorLookupAsync();
|
||||
|
||||
Task AddTranslationsAsync(Guid id, AddBookTranslationDto input); // added this line
|
||||
}
|
||||
```
|
||||
|
||||
#### Acme.BookStore.Application
|
||||
|
||||
Now, we need to implement the `AddTranslationsAsync` method in `BookAppService` and include `Translations` in the `Book` entity, for this you can change the `BookAppService` as follows:
|
||||
|
||||
```csharp
|
||||
[Authorize(BookStorePermissions.Books.Default)]
|
||||
public class BookAppService :
|
||||
CrudAppService<
|
||||
Book, //The Book entity
|
||||
BookDto, //Used to show books
|
||||
Guid, //Primary key of the book entity
|
||||
PagedAndSortedResultRequestDto, //Used for paging/sorting
|
||||
CreateUpdateBookDto>, //Used to create/update a book
|
||||
IBookAppService //implement the IBookAppService
|
||||
{
|
||||
private readonly IAuthorRepository _authorRepository;
|
||||
|
||||
public BookAppService(
|
||||
IRepository<Book, Guid> repository,
|
||||
IAuthorRepository authorRepository)
|
||||
: base(repository)
|
||||
{
|
||||
_authorRepository = authorRepository;
|
||||
GetPolicyName = BookStorePermissions.Books.Default;
|
||||
GetListPolicyName = BookStorePermissions.Books.Default;
|
||||
CreatePolicyName = BookStorePermissions.Books.Create;
|
||||
UpdatePolicyName = BookStorePermissions.Books.Edit;
|
||||
DeletePolicyName = BookStorePermissions.Books.Create;
|
||||
}
|
||||
|
||||
public override async Task<BookDto> GetAsync(Guid id)
|
||||
{
|
||||
//Get the IQueryable<Book> from the repository
|
||||
var queryable = await Repository.WithDetailsAsync(); // this line changed
|
||||
|
||||
//Prepare a query to join books and authors
|
||||
var query = from book in queryable
|
||||
join author in await _authorRepository.GetQueryableAsync() on book.AuthorId equals author.Id
|
||||
where book.Id == id
|
||||
select new { book, author };
|
||||
|
||||
//Execute the query and get the book with author
|
||||
var queryResult = await AsyncExecuter.FirstOrDefaultAsync(query);
|
||||
if (queryResult == null)
|
||||
{
|
||||
throw new EntityNotFoundException(typeof(Book), id);
|
||||
}
|
||||
|
||||
var bookDto = ObjectMapper.Map<Book, BookDto>(queryResult.book);
|
||||
bookDto.AuthorName = queryResult.author.Name;
|
||||
return bookDto;
|
||||
}
|
||||
|
||||
public override async Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input)
|
||||
{
|
||||
//Get the IQueryable<Book> from the repository
|
||||
var queryable = await Repository.WithDetailsAsync(); // this line changed
|
||||
|
||||
//Prepare a query to join books and authors
|
||||
var query = from book in queryable
|
||||
join author in await _authorRepository.GetQueryableAsync() on book.AuthorId equals author.Id
|
||||
select new {book, author};
|
||||
|
||||
//Paging
|
||||
query = query
|
||||
.OrderBy(NormalizeSorting(input.Sorting))
|
||||
.Skip(input.SkipCount)
|
||||
.Take(input.MaxResultCount);
|
||||
|
||||
//Execute the query and get a list
|
||||
var queryResult = await AsyncExecuter.ToListAsync(query);
|
||||
|
||||
//Convert the query result to a list of BookDto objects
|
||||
var bookDtos = queryResult.Select(x =>
|
||||
{
|
||||
var bookDto = ObjectMapper.Map<Book, BookDto>(x.book);
|
||||
bookDto.AuthorName = x.author.Name;
|
||||
return bookDto;
|
||||
}).ToList();
|
||||
|
||||
//Get the total count with another query
|
||||
var totalCount = await Repository.GetCountAsync();
|
||||
|
||||
return new PagedResultDto<BookDto>(
|
||||
totalCount,
|
||||
bookDtos
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<ListResultDto<AuthorLookupDto>> GetAuthorLookupAsync()
|
||||
{
|
||||
var authors = await _authorRepository.GetListAsync();
|
||||
|
||||
return new ListResultDto<AuthorLookupDto>(
|
||||
ObjectMapper.Map<List<Author>, List<AuthorLookupDto>>(authors)
|
||||
);
|
||||
}
|
||||
|
||||
public async Task AddTranslationsAsync(Guid id, AddBookTranslationDto input)
|
||||
{
|
||||
var queryable = await Repository.WithDetailsAsync();
|
||||
|
||||
var book = await AsyncExecuter.FirstOrDefaultAsync(queryable, x => x.Id == id);
|
||||
|
||||
if (book.Translations.Any(x => x.Language == input.Language))
|
||||
{
|
||||
throw new UserFriendlyException($"Translation already available for {input.Language}");
|
||||
}
|
||||
|
||||
book.Translations.Add(new BookTranslation
|
||||
{
|
||||
BookId = book.Id,
|
||||
Name = input.Name,
|
||||
Language = input.Language
|
||||
});
|
||||
|
||||
await Repository.UpdateAsync(book);
|
||||
}
|
||||
|
||||
private static string NormalizeSorting(string sorting)
|
||||
{
|
||||
if (sorting.IsNullOrEmpty())
|
||||
{
|
||||
return $"book.{nameof(Book.Name)}";
|
||||
}
|
||||
|
||||
if (sorting.Contains("authorName", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return sorting.Replace(
|
||||
"authorName",
|
||||
"author.Name",
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
);
|
||||
}
|
||||
|
||||
return $"book.{sorting}";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Create the `MultiLingualBookObjectMapper` class as follows:
|
||||
|
||||
```csharp
|
||||
public class MultiLingualBookObjectMapper : IObjectMapper<Book, BookDto>, ITransientDependency
|
||||
{
|
||||
private readonly MultiLingualObjectManager _multiLingualObjectManager;
|
||||
|
||||
private readonly ISettingProvider _settingProvider;
|
||||
|
||||
public MultiLingualBookObjectMapper(
|
||||
MultiLingualObjectManager multiLingualObjectManager,
|
||||
ISettingProvider settingProvider)
|
||||
{
|
||||
_multiLingualObjectManager = multiLingualObjectManager;
|
||||
_settingProvider = settingProvider;
|
||||
}
|
||||
|
||||
public BookDto Map(Book source)
|
||||
{
|
||||
var translation = AsyncHelper.RunSync(() =>
|
||||
_multiLingualObjectManager.FindTranslationAsync<Book, BookTranslation>(source));
|
||||
|
||||
return new BookDto
|
||||
{
|
||||
Id = source.Id,
|
||||
AuthorId = source.AuthorId,
|
||||
Type = source.Type,
|
||||
Name = translation?.Name ?? source.Name,
|
||||
PublishDate = source.PublishDate,
|
||||
Price = source.Price,
|
||||
Language = translation?.Language ?? AsyncHelper.RunSync(() => _settingProvider.GetOrNullAsync(LocalizationSettingNames.DefaultLanguage)),
|
||||
CreationTime = source.CreationTime,
|
||||
CreatorId = source.CreatorId,
|
||||
LastModificationTime = source.LastModificationTime,
|
||||
LastModifierId = source.LastModifierId
|
||||
};
|
||||
}
|
||||
|
||||
public BookDto Map(Book source, BookDto destination)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To map the multi-lingual `Book` entity to `BookDto`, we implement custom mapping using the `IObjectMapper<TSource, TDestination>` interface. If no translation is found, default values are returned.
|
||||
|
||||
So far we have created the entire infrastructure. We don't need to change anything in the UI, if there is a translation according to the language chosen by the user, the list view will change. However, I want to create a simple modal where we can add new translations to an existing book in order to see what we have done.
|
||||
|
||||
#### Acme.BookStore.Web
|
||||
|
||||
Create a new razor page named `AddTranslationModal` in the `Books` folder as below.
|
||||
|
||||
**View**
|
||||
|
||||
```html
|
||||
@page
|
||||
@using Microsoft.AspNetCore.Mvc.TagHelpers
|
||||
@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
|
||||
@model Acme.BookStore.Web.Pages.Books.AddTranslationModal
|
||||
|
||||
@{
|
||||
Layout = null;
|
||||
}
|
||||
|
||||
<form asp-page="/Books/AddTranslationModal">
|
||||
<abp-modal>
|
||||
<abp-modal-header>Translations</abp-modal-header>
|
||||
<abp-modal-body>
|
||||
<abp-input asp-for="Id"></abp-input>
|
||||
<abp-select asp-for="@Model.TranslationViewModel.Language" asp-items="Model.Languages" class="form-select">
|
||||
<option selected value="">Pick a language</option>
|
||||
</abp-select>
|
||||
<abp-input asp-for="TranslationViewModel.Name"></abp-input>
|
||||
</abp-modal-body>
|
||||
<abp-modal-footer buttons="@(AbpModalButtons.Cancel | AbpModalButtons.Save)"></abp-modal-footer>
|
||||
</abp-modal>
|
||||
</form>
|
||||
```
|
||||
|
||||
**Model**
|
||||
|
||||
```csharp
|
||||
public class AddTranslationModal : BookStorePageModel
|
||||
{
|
||||
[HiddenInput]
|
||||
[BindProperty(SupportsGet = true)]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public List<SelectListItem> Languages { get; set; }
|
||||
|
||||
[BindProperty]
|
||||
public BookTranslationViewModel TranslationViewModel { get; set; }
|
||||
|
||||
private readonly IBookAppService _bookAppService;
|
||||
private readonly ILanguageProvider _languageProvider;
|
||||
|
||||
public AddTranslationModal(
|
||||
IBookAppService bookAppService,
|
||||
ILanguageProvider languageProvider)
|
||||
{
|
||||
_bookAppService = bookAppService;
|
||||
_languageProvider = languageProvider;
|
||||
}
|
||||
|
||||
public async Task OnGetAsync()
|
||||
{
|
||||
Languages = await GetLanguagesSelectItem();
|
||||
|
||||
TranslationViewModel = new BookTranslationViewModel();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> OnPostAsync()
|
||||
{
|
||||
await _bookAppService.AddTranslationsAsync(Id, ObjectMapper.Map<BookTranslationViewModel, AddBookTranslationDto>(TranslationViewModel));
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
private async Task<List<SelectListItem>> GetLanguagesSelectItem()
|
||||
{
|
||||
var result = await _languageProvider.GetLanguagesAsync();
|
||||
|
||||
return result.Select(
|
||||
languageInfo => new SelectListItem
|
||||
{
|
||||
Value = languageInfo.CultureName,
|
||||
Text = languageInfo.DisplayName + " (" + languageInfo.CultureName + ")"
|
||||
}
|
||||
).ToList();
|
||||
}
|
||||
|
||||
public class BookTranslationViewModel
|
||||
{
|
||||
[Required]
|
||||
[SelectItems(nameof(Languages))]
|
||||
public string Language { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Name { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then, we can open the `BookStoreWebAutoMapperProfile` class and define the required mapping as follows:
|
||||
|
||||
```csharp
|
||||
CreateMap<AddTranslationModal.BookTranslationViewModel, AddBookTranslationDto>();
|
||||
```
|
||||
|
||||
Finally, change the content of `index.js` in the `Books` folder as follows:
|
||||
|
||||
```javascript
|
||||
$(function () {
|
||||
var l = abp.localization.getResource('BookStore');
|
||||
var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal');
|
||||
var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal');
|
||||
var addTranslationModal = new abp.ModalManager(abp.appPath + 'Books/AddTranslationModal'); // added this line
|
||||
|
||||
var dataTable = $('#BooksTable').DataTable(
|
||||
abp.libs.datatables.normalizeConfiguration({
|
||||
serverSide: true,
|
||||
paging: true,
|
||||
order: [[1, "asc"]],
|
||||
searching: false,
|
||||
scrollX: true,
|
||||
ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList),
|
||||
columnDefs: [
|
||||
{
|
||||
title: l('Actions'),
|
||||
rowAction: {
|
||||
items:
|
||||
[
|
||||
{
|
||||
text: l('Edit'),
|
||||
visible: abp.auth.isGranted('BookStore.Books.Edit'),
|
||||
action: function (data) {
|
||||
editModal.open({ id: data.record.id });
|
||||
}
|
||||
},
|
||||
{
|
||||
text: l('Add Translation'), // added this action
|
||||
visible: abp.auth.isGranted('BookStore.Books.Edit'),
|
||||
action: function (data) {
|
||||
addTranslationModal.open({ id: data.record.id });
|
||||
}
|
||||
},
|
||||
{
|
||||
text: l('Delete'),
|
||||
visible: abp.auth.isGranted('BookStore.Books.Delete'),
|
||||
confirmMessage: function (data) {
|
||||
return l(
|
||||
'BookDeletionConfirmationMessage',
|
||||
data.record.name
|
||||
);
|
||||
},
|
||||
action: function (data) {
|
||||
acme.bookStore.books.book
|
||||
.delete(data.record.id)
|
||||
.then(function() {
|
||||
abp.notify.info(
|
||||
l('SuccessfullyDeleted')
|
||||
);
|
||||
dataTable.ajax.reload();
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
title: l('Name'),
|
||||
data: "name"
|
||||
},
|
||||
{
|
||||
title: l('Author'),
|
||||
data: "authorName"
|
||||
},
|
||||
{
|
||||
title: l('Type'),
|
||||
data: "type",
|
||||
render: function (data) {
|
||||
return l('Enum:BookType:' + data);
|
||||
}
|
||||
},
|
||||
{
|
||||
title: l('PublishDate'),
|
||||
data: "publishDate",
|
||||
render: function (data) {
|
||||
return luxon
|
||||
.DateTime
|
||||
.fromISO(data, {
|
||||
locale: abp.localization.currentCulture.name
|
||||
}).toLocaleString();
|
||||
}
|
||||
},
|
||||
{
|
||||
title: l('Price'),
|
||||
data: "price"
|
||||
},
|
||||
{
|
||||
title: l('CreationTime'),
|
||||
data: "creationTime",
|
||||
render: function (data) {
|
||||
return luxon
|
||||
.DateTime
|
||||
.fromISO(data, {
|
||||
locale: abp.localization.currentCulture.name
|
||||
}).toLocaleString(luxon.DateTime.DATETIME_SHORT);
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
createModal.onResult(function () {
|
||||
dataTable.ajax.reload();
|
||||
});
|
||||
|
||||
editModal.onResult(function () {
|
||||
dataTable.ajax.reload();
|
||||
});
|
||||
|
||||
$('#NewBookButton').click(function (e) {
|
||||
e.preventDefault();
|
||||
createModal.open();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
With a multi-lingual application, you can expand your market share, but if not designed well, may your application will be unusable. So, I've tried to explain how to design a sustainable multi-lingual entity in this article.
|
||||
|
||||
### Source Code
|
||||
|
||||
You can find source code of the example solution used in this article [here](https://github.com/abpframework/abp-samples/tree/master/AcmeBookStoreMultiLingual).
|
||||
|
After Width: | Height: | Size: 172 KiB |
|
After Width: | Height: | Size: 2.7 MiB |
@ -0,0 +1,154 @@
|
||||
# How to Add Custom Properties to the User Entity
|
||||
|
||||
> **Note:** If your application is less than version 4.4.x, please follow [this article](../2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/How-To-Add-Custom-Property-To-The-User-Entity.md).
|
||||
|
||||
## Introduction
|
||||
|
||||
In this step-by-step article, I will explain how you can customize the user entity class, which is available in every web application you create using the ABP framework, according to your needs. When you read this article, you will learn how to override the services of built-in modules, extend the entities, extend data transfer objects and customize the user interface in the applications you develop using the ABP framework.
|
||||
|
||||
> **Note:** This article is not about customizing the `Login` page. If you have such a need, please follow [this article](../2020-05-09-Customize-the-Login-Page-for-MVC-Razor-Page-Applications/POST.md).
|
||||
|
||||
You can see the screenshots below which we will reach at the end of the article.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Preparing the Project
|
||||
|
||||
### Startup template and the initial run
|
||||
|
||||
Abp Framework offers startup templates to get into the work faster. We can create a new startup template using Abp CLI:
|
||||
|
||||
`abp new CustomizeUserDemo`
|
||||
|
||||
> In this article, I will go through the MVC application, but it will work also in the [Angular](https://docs.abp.io/en/abp/latest/Getting-Started?UI=NG&DB=EF&Tiered=No), [Blazor Server](https://docs.abp.io/en/abp/latest/Getting-Started?UI=BlazorServer&DB=EF&Tiered=No), and [Blazor WebAssembly](https://docs.abp.io/en/abp/latest/Getting-Started?UI=Blazor&DB=EF&Tiered=No) application.
|
||||
|
||||
After the download is finished, we can run **CustomizeUserDemo.DbMigrator** project to create the database migrations and seed the initial data (admin user, role, etc). Then we can run `CustomizeUserDemo.Web` to see that our application is working.
|
||||
|
||||
> Default admin username is **admin** and password is **1q2w3E\***
|
||||
|
||||

|
||||
|
||||
In this article, we will go through a scenario together and find the solutions to our questions through this scenario. However, since the scenario is not a real-life scenario, it may be strange, please don't get too about this issue :)
|
||||
|
||||
## Step-1
|
||||
|
||||
Create the Users folder in the **CustomizeUserDemo.Domain.Shared** project, create the class `UserConsts` inside the folder and update the class you created as below:
|
||||
|
||||
```csharp
|
||||
public static class UserConsts
|
||||
{
|
||||
public const string TitlePropertyName = "Title";
|
||||
|
||||
public const string ReputationPropertyName = "Reputation";
|
||||
|
||||
public const int MaxTitleLength = 64;
|
||||
|
||||
public const double MaxReputationValue = 1_000;
|
||||
|
||||
public const double MinReputationValue = 1;
|
||||
}
|
||||
```
|
||||
|
||||
## Step-2
|
||||
|
||||
Update the `CustomizeUserDemoEfCoreEntityExtensionMappings` class in the **CustomizeUserDemo.EntityFramework** project in the EntityFrameworkCore folder as below:
|
||||
|
||||
```csharp
|
||||
public static class CustomizeUserDemoEfCoreEntityExtensionMappings
|
||||
{
|
||||
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
|
||||
|
||||
public static void Configure()
|
||||
{
|
||||
CustomizeUserDemoGlobalFeatureConfigurator.Configure();
|
||||
CustomizeUserDemoModuleExtensionConfigurator.Configure();
|
||||
|
||||
OneTimeRunner.Run(() =>
|
||||
{
|
||||
ObjectExtensionManager.Instance
|
||||
.MapEfCoreProperty<IdentityUser, string>(
|
||||
UserConsts.TitlePropertyName,
|
||||
(_, propertyBuilder) =>
|
||||
{
|
||||
propertyBuilder.HasDefaultValue("");
|
||||
propertyBuilder.HasMaxLength(UserConsts.MaxTitleLength);
|
||||
}
|
||||
).MapEfCoreProperty<IdentityUser, int>(
|
||||
UserConsts.ReputationPropertyName,
|
||||
(_, propertyBuilder) =>
|
||||
{
|
||||
propertyBuilder.HasDefaultValue(UserConsts.MinReputationValue);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This class can be used to map these extra properties to table fields in the database. Please read [this](https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities) article to improve your understanding of what we are doing.
|
||||
|
||||
So far, we have added our extra features to the `User` entity and matched these features with the `ef core`.
|
||||
|
||||
Now we need to add migration to see what has changed in our database. This for, open the Package Manager Console (PMC) under the menu Tools > NuGet Package Manager.
|
||||
|
||||

|
||||
|
||||
Select the **CustomizeUserDemo.EntityFramework** as the **default project** and execute the following command:
|
||||
|
||||
```bash
|
||||
Add-Migration "Updated-User-Entity"
|
||||
```
|
||||
|
||||

|
||||
|
||||
This will create a new migration class inside the `Migrations` folder of the **CustomizeUserDemo.EntityFrameworkCore** project.
|
||||
|
||||
> If you are using another IDE than the Visual Studio, you can use `dotnet-ef` tool as [documented here](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli#create-a-migration).
|
||||
|
||||
Finally, run the **CustomizeUserDemo.DbMigrator** project to update the database.
|
||||
|
||||
When we updated the database, you can see that the `Title` and `Reputation` columns are added to the `Users` table.
|
||||
|
||||

|
||||
|
||||
## Step-3
|
||||
Open the `CustomizeUserDemoModuleExtensionConfigurator` in the **CustomizeUserDemo.Domain.Shared** project, and change the contents of the `ConfigureExtraProperties` method as shown below:
|
||||
```csharp
|
||||
private static void ConfigureExtraProperties()
|
||||
{
|
||||
ObjectExtensionManager.Instance.Modules().ConfigureIdentity(identity =>
|
||||
{
|
||||
identity.ConfigureUser(user =>
|
||||
{
|
||||
user.AddOrUpdateProperty<string>(
|
||||
UserConsts.TitlePropertyName,
|
||||
options =>
|
||||
{
|
||||
options.Attributes.Add(new RequiredAttribute());
|
||||
options.Attributes.Add(
|
||||
new StringLengthAttribute(UserConsts.MaxTitleLength)
|
||||
);
|
||||
}
|
||||
);
|
||||
user.AddOrUpdateProperty<int>(
|
||||
UserConsts.ReputationPropertyName,
|
||||
options =>
|
||||
{
|
||||
options.DefaultValue = UserConsts.MinReputationValue;
|
||||
options.Attributes.Add(
|
||||
new RangeAttribute(UserConsts.MinReputationValue, UserConsts.MaxReputationValue)
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
That's it. Now let's run the application and look at the Identity user page. You can also try to edit and recreate a record if you want, it will work even though we haven't done anything extra. Here is the magic code behind ABP framework.
|
||||
|
||||
If there is a situation you want to add, you can click the contribute button or make a comment. Also, if you like the article, don't forget to share it :)
|
||||
|
||||
Happy coding :)
|
||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 193 KiB |
@ -0,0 +1,244 @@
|
||||
# Using gRPC with the ABP Framework
|
||||
|
||||
[gRPC](https://grpc.io/) defines itself as an open source, language agnostic, universal, high-performance **Remote Procedure Call (RPC)** framework.
|
||||
|
||||
In this article, I will show you how to create a gRPC service and consume it from a console application with the ABP Framework. While the client application is console in this article, it can easily be a service consuming another service in a microservice system.
|
||||
|
||||
> **This article will be a step by step tutorial.** I wrote the article based on Microsoft's [Code-first gRPC services and clients with .NET](https://docs.microsoft.com/en-us/aspnet/core/grpc/code-first) document. You can read that document for more details about gRPC and the code-first approach.
|
||||
|
||||
## Creating the Application
|
||||
|
||||
> I will use ABP version 6.0 for this article. I am using the 6.0.0-rc.4 version since the stable version hasn't been published at the time I am writing this article. If it is released while you're reading this, do not specify the `--version` and `--preview` parameters in the following commands.
|
||||
|
||||
Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed it yet:
|
||||
|
||||
````bash
|
||||
dotnet tool install -g Volo.Abp.Cli --version 6.0.0-rc.4
|
||||
````
|
||||
|
||||
or update to version 6.0.0-rc.4 if you've already installed a previous version:
|
||||
|
||||
````bash
|
||||
dotnet tool update Volo.Abp.Cli -g --version 6.0.0-rc.4
|
||||
````
|
||||
|
||||
Create an empty folder, open a command-line terminal and type the following command in the terminal window to create a new ABP solution using the ABP CLI:
|
||||
|
||||
````bash
|
||||
abp new ProductManagement -u blazor -t app --preview
|
||||
````
|
||||
|
||||
I've created an application with the Blazor UI, but the UI is not important for this tutorial, you can select your favorite UI option.
|
||||
|
||||
## Open the Solution
|
||||
|
||||
Open the solution in your favorite IDE. I like [Rider](https://www.jetbrains.com/rider/), but Visual Studio, VS Code or any other IDE perfectly works. The following figure shows the solution structure in Rider:
|
||||
|
||||

|
||||
|
||||
Run the `ProductManagement.DbMigrator` project (a console application) to create the database and seed the initial data.
|
||||
|
||||
## Defining the Service Contract
|
||||
|
||||
We are starting by defining the service contract and DTO classes that will be shared between the server and the client applications.
|
||||
|
||||
Create a `Products` folder in the `ProductManagement.Application.Contracts` project and add a new interface named `IProductAppService`:
|
||||
|
||||
````csharp
|
||||
using System.Collections.Generic;
|
||||
using System.ServiceModel;
|
||||
using System.Threading.Tasks;
|
||||
using Volo.Abp.Application.Services;
|
||||
|
||||
namespace ProductManagement.Products;
|
||||
|
||||
[ServiceContract]
|
||||
public interface IProductAppService : IApplicationService
|
||||
{
|
||||
Task<List<ProductDto>> GetListAsync();
|
||||
}
|
||||
````
|
||||
|
||||
Your IDE will complain about the `[ServiceContract]` attribute, but it is necessary for the contract-first gRPC library we will be using later. So, add the [System.ServiceModel.Primitives](https://www.nuget.org/packages/System.ServiceModel.Primitives) NuGet package to the `ProductManagement.Application.Contracts` project, and it should be fixed. You can simply edit the `ProductManagement.Application.Contracts.csproj` file and add the following line in an `ItemGroup` tag:
|
||||
|
||||
````xml
|
||||
<PackageReference Include="System.ServiceModel.Primitives" Version="4.7.0" />
|
||||
````
|
||||
|
||||
Or you can use your IDE to find and add that NuGet package, it is up to you.
|
||||
|
||||
I've also used the `ProductDto` class, but haven't defined it yet. Create a new class in the same folder with the `IProductAppService` file:
|
||||
|
||||
````csharp
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProductManagement.Products;
|
||||
|
||||
[DataContract]
|
||||
public class ProductDto
|
||||
{
|
||||
[DataMember(Order = 1)]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[DataMember(Order = 2)]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
````
|
||||
|
||||
The `[DataContract]` and `[DataMember]` properties are needed for serialization. In gRPC, property serialization orders are important, because property names are not transferred to the target application, to keep the serialized data small.
|
||||
|
||||
After adding these classes, the `ProductManagement.Application.Contracts` project should look as in the following figure:
|
||||
|
||||

|
||||
|
||||
The contracts part is over. We actually didn't have any dependency to gRPC at that point. Our service and DTOs are pretty plain classes, except a few standard attributes, which are already defined in the .NET Core framework. Now, we can implement the `IProductAppService`.
|
||||
|
||||
## Implementing the Service
|
||||
|
||||
We are implementing the application services in the `ProductManagement.Application` project. So, add a new `Products` folder to that project and define a `ProductAppService` class inside it:
|
||||
|
||||
````csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProductManagement.Products;
|
||||
|
||||
public class ProductAppService : ProductManagementAppService, IProductAppService
|
||||
{
|
||||
public async Task<List<ProductDto>> GetListAsync()
|
||||
{
|
||||
return new List<ProductDto>
|
||||
{
|
||||
new ProductDto { Id = Guid.NewGuid(), Name = "Product 1" },
|
||||
new ProductDto { Id = Guid.NewGuid(), Name = "Product 2" },
|
||||
};
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
This is a pretty standard, plain [application service ](https://docs.abp.io/en/abp/latest/Application-Services)class. All the ABP application service features (validation, audit logging, unit of work, etc.) are available. You can inject [repositories](https://docs.abp.io/en/abp/latest/Repositories) and perform database queries. To keep this article simple, I am returning hard-coded data from here.
|
||||
|
||||
> `ProductManagementAppService` is a base class coming in the ABP startup template. While you don't have to inherit from it, it provides useful base properties and methods you typically need in an application service.
|
||||
|
||||
The application service part is over. Again, we didn't write any gRPC specific code. Don't worry, we will write in the next section.
|
||||
|
||||
## Configuring the gRPC Server
|
||||
|
||||
In this solution, `ProductManagement.HttpApi.Host` is the project that configures and runs the server-side application. So, we will make changes in that project.
|
||||
|
||||
First, add the [protobuf-net.Grpc.AspNetCore](https://www.nuget.org/packages/protobuf-net.Grpc.AspNetCore) NuGet package to the `ProductManagement.HttpApi.Host` project:
|
||||
|
||||
````xml
|
||||
<PackageReference Include="protobuf-net.Grpc.AspNetCore" Version="1.0.177" />
|
||||
````
|
||||
|
||||
Then open the `ProductManagementHttpApiHostModule.cs` file, find the `ConfigureServices` method and add the following line into this method:
|
||||
|
||||
````csharp
|
||||
context.Services.AddCodeFirstGrpc();
|
||||
````
|
||||
|
||||
This will register code-first gRPC services to the [dependency injection](https://docs.abp.io/en/abp/latest/Dependency-Injection) system. Then find the `app.UseConfiguredEndpoints()` line in the `OnApplicationInitialization` method and change it as shown below:
|
||||
|
||||
````csharp
|
||||
app.UseConfiguredEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapGrpcService<IProductAppService>();
|
||||
});
|
||||
````
|
||||
|
||||
We've configured the `IProductAppService` to handle gRPC requests to that service. The following figure shows the whole change done in the `ProductManagementHttpApiHostModule` class:
|
||||
|
||||

|
||||
|
||||
gRPC handles requests with the HTTP/2 protocol and should listen an endpoint other than the default HTTP endpoint used by the application. We can easily configure the Kestrel server to listen two endpoints, one for our HTTP APIs, the other one for gRPC services. Add the following configuration inside the `appsettings.json` file of the `ProductManagement.HttpApi.Host` project:
|
||||
|
||||
````json
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Https": {
|
||||
"Url": "https://localhost:44388",
|
||||
"Protocols": "Http1AndHttp2"
|
||||
},
|
||||
"gRPC": {
|
||||
"Url": "https://localhost:10042",
|
||||
"Protocols": "Http2"
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
Note that `https://localhost:44388` may be different for your case, since ABP CLI assignes a random port while you're creating a new solution. You can check your port by running the `ProductManagement.HttpApi.Host` project and looking at the address bar on your browser.
|
||||
|
||||
The server-side configuration is done. It is ready to receive gRPC requests. Now, we can change the client to consume the gRPC service we've created.
|
||||
|
||||
## Implementing the Client Side
|
||||
|
||||
The ABP startup solution template comes with a console application to test consuming your HTTP APIs. For this example, the project is named as `ProductManagement.HttpApi.Client.ConsoleTestApp` and located under the `test` folder in the solution.
|
||||
|
||||
First, add the [Grpc.Net.Client](https://www.nuget.org/packages/Grpc.Net.Client) and the [protobuf-net.Grpc](https://www.nuget.org/packages/protobuf-net.Grpc) NuGet packages to the `ProductManagement.HttpApi.Client.ConsoleTestApp` project.
|
||||
|
||||
````xml
|
||||
<PackageReference Include="Grpc.Net.Client" Version="2.49.0-pre1" />
|
||||
<PackageReference Include="protobuf-net.Grpc" Version="1.0.177" />
|
||||
````
|
||||
|
||||
Now, open the `ClientDemoService.cs` file under the `ProductManagement.HttpApi.Client.ConsoleTestApp` project and change its contents with the following code block:
|
||||
|
||||
````csharp
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Grpc.Net.Client;
|
||||
using ProductManagement.Products;
|
||||
using ProtoBuf.Grpc.Client;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
|
||||
namespace ProductManagement.HttpApi.Client.ConsoleTestApp;
|
||||
|
||||
public class ClientDemoService : ITransientDependency
|
||||
{
|
||||
public async Task RunAsync()
|
||||
{
|
||||
using (var channel = GrpcChannel.ForAddress("https://localhost:10042"))
|
||||
{
|
||||
var productAppService = channel.CreateGrpcService<IProductAppService>();
|
||||
var productDtos = await productAppService.GetListAsync();
|
||||
|
||||
foreach (var productDto in productDtos)
|
||||
{
|
||||
Console.WriteLine($"[Product] Id = {productDto.Id}, Name = {productDto.Name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
We are simply creating a gRPC channel, then creating a client proxy for the `IProductAppService` service. Then we can call its method just like local method calls. You can run the applications to test it.
|
||||
|
||||
## Run the Applications
|
||||
|
||||
First run the `ProductManagement.HttpApi.Host` application. It should show a Swagger UI as shown below:
|
||||
|
||||

|
||||
|
||||
If you see that page, it means your server-side is up and running. Now, you can run the `ProductManagement.HttpApi.Client.ConsoleTestApp` console application to call the gRPC service defined on the server.
|
||||
|
||||
The test console application should produce an output as shown below:
|
||||
|
||||

|
||||
|
||||
As you see, products are returned from the server. That's all, you've done it!
|
||||
|
||||
## Conclusion
|
||||
|
||||
In this article, I've used the [code-first approach](https://docs.microsoft.com/en-us/aspnet/core/grpc/code-first) to implement a gRPC server and consume it in a client application. Code-first approach is very practical if both of your client and server applications are built with .NET. By the help of ABP's layered solution structure, we even didn't add any gRPC dependency into our server-side and contracts. We've just configured gRPC in the hosting side, with a small amount of code.
|
||||
|
||||
gRPC on .NET has different approaches, features, configurations and more details. I suggest you to read [Microsoft's documentation](https://docs.microsoft.com/en-us/aspnet/core/grpc) to learn more about it. All the approaches can work with the ABP Framework. Enjoy coding!
|
||||
|
||||
## The Source Code
|
||||
|
||||
* You can find the completed source code here: https://github.com/abpframework/abp-samples/tree/master/GrpcDemo2
|
||||
|
||||
* You can also see all the changes I've done in this article here: https://github.com/abpframework/abp-samples/pull/200/files
|
||||
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 48 KiB |
@ -0,0 +1,121 @@
|
||||
# Consuming gRPC Services from Blazor WebAssembly Application Using gRPC-Web
|
||||
|
||||
> **WARNING: I've demonstrated [Using gRPC with the ABP Framework](https://community.abp.io/posts/using-grpc-with-the-abp-framework-2dgaxzw3) in my latest post. If you haven't seen it, you should read it before this article, since this is a continuation of that article.**
|
||||
|
||||
In this second part, I will show how to consume the gRPC service from the Blazor WebAssembly application, using the gRPC-Web technology.
|
||||
|
||||
This will be a short article, based on Microsoft's [gRPC-Web in ASP.NET Core gRPC apps](https://learn.microsoft.com/en-us/aspnet/core/grpc/grpcweb) and [Code-first gRPC services and clients with .NET](https://learn.microsoft.com/en-us/aspnet/core/grpc/code-first) documents. For more information, I suggest to check these documents. Let's get started...
|
||||
|
||||
## Configuring the Server Side
|
||||
|
||||
First of all, the server-side should support gRPC-Web. Follow the steps below to enable it:
|
||||
|
||||
### Add Grpc.AspNetCore.Web Package
|
||||
|
||||
Add [Grpc.AspNetCore.Web](https://www.nuget.org/packages/Grpc.AspNetCore.Web) NuGet package to the `ProductManagement.HttpApi.Host` project.
|
||||
|
||||
### Add GrpcWeb Middleware
|
||||
|
||||
Add the following line just before the `app.UseConfiguredEndpoints(...)` line to add the GrpcWeb middleware to your ASP.NET Core request pipeline:
|
||||
|
||||
````csharp
|
||||
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
|
||||
````
|
||||
|
||||
### Configure Cors
|
||||
|
||||
ABP's startup template already configures Cors when you create a new solution. However, we need to allow some extra headers in our Cors configuration.
|
||||
|
||||
Add the following line just after the `.WithAbpExposedHeaders()` line in the `OnApplicationInitialization` method of the `ProductManagementHttpApiHostModule` class:
|
||||
|
||||
````csharp
|
||||
.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding")
|
||||
````
|
||||
|
||||
Finally, call `RequireCors` extension method just after the `MapGrpcService` calls:
|
||||
|
||||
````csharp
|
||||
app.UseConfiguredEndpoints(endpoints =>
|
||||
{
|
||||
endpoints
|
||||
.MapGrpcService<IProductAppService>()
|
||||
.RequireCors("__DefaultCorsPolicy"); // Configure Cors for the product service
|
||||
});
|
||||
````
|
||||
|
||||
`__DefaultCorsPolicy` may seem a magic string here. Let me explain it: ABP startup template configures the default Cors policy with the `context.Services.AddCors(...)` method (you can see it in the source code). If we define a named policy, we should use the same name here. However, when we don't specify, ASP.NET Core uses `__DefaultCorsPolicy` as the policy name by default. If you don't want to use the magic string, you can resolve the `IOptions<CorsOptions>` service and get the `DefaultPolicyName` from the `CorsOption` object.
|
||||
|
||||
Anyway, that's all on the server-side. We can work on he client now.
|
||||
|
||||
## Configuring the Client Side
|
||||
|
||||
`ProductManagement.Blazor` is the Blazor WebAssembly application in the solution I'd created in the [first article](https://community.abp.io/posts/using-grpc-with-the-abp-framework-2dgaxzw3). We will configure that project to be able to consume the server-side gRPC services from our Blazor application.
|
||||
|
||||
### Add Client-side Nuget Packages
|
||||
|
||||
Add [Grpc.Net.Client](https://www.nuget.org/packages/Grpc.Net.Client), [Grpc.Net.Client.Web](https://www.nuget.org/packages/Grpc.Net.Client.Web) and [protobuf-net.Grpc](https://www.nuget.org/packages/protobuf-net.Grpc) NuGet packages to the `ProductManagement.Blazor` project. We are ready to consume the gRPC services.
|
||||
|
||||
### Consume the Product Service
|
||||
|
||||
Change the `Pages/Index.razor.cs` file's content with the following code block:
|
||||
|
||||
````csharp
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Grpc.Net.Client;
|
||||
using Grpc.Net.Client.Web;
|
||||
using ProductManagement.Products;
|
||||
using ProtoBuf.Grpc.Client;
|
||||
|
||||
namespace ProductManagement.Blazor.Pages;
|
||||
|
||||
public partial class Index
|
||||
{
|
||||
private List<ProductDto> Products { get; set; } = new();
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var channel = GrpcChannel.ForAddress("https://localhost:10042", new GrpcChannelOptions
|
||||
{
|
||||
HttpHandler = new GrpcWebHandler(new HttpClientHandler())
|
||||
});
|
||||
|
||||
var productAppService = channel.CreateGrpcService<IProductAppService>();
|
||||
Products = await productAppService.GetListAsync();
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
* We've created a gRPC channel for the server-side endpoint (surely, you get the address from a configuration) with channel options by specifying that we will use the `GrpcWebHandler`.
|
||||
* We've created a service proxy object using the `CreateGrpcService` extension method that is defined by the [protobuf-net.Grpc](https://www.nuget.org/packages/protobuf-net.Grpc) NuGet package.
|
||||
* We've used the service proxy object, `productAppService`, to consume remote endpoint just like a local service.
|
||||
|
||||
That's all. If we want to show the products on the page, we can add the following markup into the `Pages/Index.razor` view:
|
||||
|
||||
````xml
|
||||
<h2>A list of products:</h2>
|
||||
|
||||
<ul class="list-group">
|
||||
@foreach(var product in Products)
|
||||
{
|
||||
<li class="list-group-item">
|
||||
@product.Name <br/>
|
||||
<small>@product.Id.ToString()</small>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
````
|
||||
|
||||
Run the applications (first run the `ProductManagement.HttpApi.Host` project, then run the `ProductManagement.Blazor` project in the solution) to see it in action:
|
||||
|
||||

|
||||
|
||||
## Conclusion
|
||||
|
||||
In the first part of this article, I'd demonstrated how to implement a gRPC service and consume it in a client application, using the [code-first approach](https://docs.microsoft.com/en-us/aspnet/core/grpc/code-first). In this article, I've demonstrated how to consume the same gRPC service from a Blazor WebAssembly application, using the [gRPC-Web](https://learn.microsoft.com/en-us/aspnet/core/grpc/grpcweb) technology. As you see in these two articles, using gRPC with the ABP Framework is straightforward.
|
||||
|
||||
## The Source Code
|
||||
|
||||
- You can find the completed source code here: https://github.com/abpframework/abp-samples/tree/master/GrpcDemo2
|
||||
- You can also see all the changes I've done in this article here: https://github.com/abpframework/abp-samples/pull/201/files
|
||||
|
After Width: | Height: | Size: 10 KiB |
@ -0,0 +1,469 @@
|
||||
# ABP Dapr Integration
|
||||
|
||||
> This document assumes that you are already familiar with [Dapr](https://dapr.io/) and you want to use it in your ABP based applications.
|
||||
|
||||
[Dapr](https://dapr.io/) (Distributed Application Runtime) provides APIs that simplify microservice connectivity. It is an open source project that is mainly backed by Microsoft. It is also a CNCF (Cloud Native Computing Foundation) project and trusted by the community.
|
||||
|
||||
ABP and Dapr have some intersecting features like service-to-service communication, distributed message bus and distributed locking. However their purposes are totally different. ABP's goal is to provide an end-to-end developer experience by offering an opinionated architecture and providing the necessary infrastructure libraries, reusable modules and tools to implement that architecture properly. Dapr's purpose, on the other hand, is to provide a runtime to decouple common microservice communication patterns from your application logic.
|
||||
|
||||
ABP and Dapr can perfectly work together in the same application. ABP offers some packages to provide better integration where Dapr features intersect with ABP. You can use other Dapr features with no ABP integration packages based on [its own documentation](https://docs.dapr.io/).
|
||||
|
||||
## ABP Dapr Integration Packages
|
||||
|
||||
ABP provides the following NuGet packages for the Dapr integration:
|
||||
|
||||
* [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr): The main Dapr integration package. All other packages depend on this package.
|
||||
* [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr): Integration package for ABP's [dynamic](../API/Dynamic-CSharp-API-Clients.md) and [static](../API/Static-CSharp-API-Clients.md) C# API Client Proxies systems with Dapr's [service invocation](https://docs.dapr.io/developing-applications/building-blocks/service-invocation/service-invocation-overview/) building block.
|
||||
* [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr): Implements ABP's distributed event bus with Dapr's [publish & subscribe](https://docs.dapr.io/developing-applications/building-blocks/pubsub/) building block. With this package, you can send events, but can not receive.
|
||||
* [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus): Provides the endpoints to receive events from Dapr's [publish & subscribe](https://docs.dapr.io/developing-applications/building-blocks/pubsub/) building block. Use this package to send and receive events.
|
||||
* [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr): Uses Dapr's [distributed lock](https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/) building block for [distributed locking](../Distributed-Locking.md) service of the ABP Framework.
|
||||
|
||||
In the following sections, we will see how to use these packages to use Dapr in your ABP based solutions.
|
||||
|
||||
## Basics
|
||||
|
||||
### Installation
|
||||
|
||||
> This section explains how to add [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr), the core Dapr integration package to your project. If you are using one of the other Dapr integration packages, you can skip this section since this package will be indirectly added.
|
||||
|
||||
Use the ABP CLI to add the [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr) NuGet package to your project:
|
||||
|
||||
* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed it before.
|
||||
* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.Dapr` package.
|
||||
* Run the `abp add-package Volo.Abp.Dapr` command.
|
||||
|
||||
If you want to do it manually, install the [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr) NuGet package to your project and add `[DependsOn(typeof(AbpDaprModule))]` to the [ABP module](../Module-Development-Basics.md) class inside your project.
|
||||
|
||||
### AbpDaprOptions
|
||||
|
||||
`AbpDaprOptions` is the main [options class](../Options.md) that you can configure the global Dapr settings with. **All settings are optional and you mostly don't need to configure them.** If you need, you can configure it in the `ConfigureServices` method of your [module class](../Module-Development-Basics.md):
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
// ...
|
||||
});
|
||||
````
|
||||
|
||||
Available properties of the `AbpDaprOptions` class:
|
||||
|
||||
* `HttpEndpoint` (optional): HTTP endpoint that is used while creating a `DaprClient` object. If you don't specify, the default value is used.
|
||||
* `GrpcEndpoint` (optional): The gRPC endpoint that is used while creating a `DaprClient` object. If you don't specify, the default value is used.
|
||||
* `DaprApiToken` (optional): The [Dapr API token](https://docs.dapr.io/operations/security/api-token/) that is used while sending requests from the application to Dapr. It is filled from the `DAPR_API_TOKEN` environment variable by default (which is set by Dapr once it is configured). See the *Security* section in this document for details.
|
||||
* `AppApiToken` (optional): The [App API token](https://docs.dapr.io/operations/security/app-api-token/) that is used to validate requests coming from Dapr. It is filled from the `APP_API_TOKEN` environment variable by default (which is set by Dapr once it is configured). See the *Security* section in this document for details.
|
||||
|
||||
Alternatively, you can configure the options in the `Dapr` section of your `appsettings.json` file. Example:
|
||||
|
||||
````csharp
|
||||
"Dapr": {
|
||||
"HttpEndpoint": "http://localhost:3500/"
|
||||
}
|
||||
````
|
||||
|
||||
### Injecting DaprClient
|
||||
|
||||
ABP registers the `DaprClient` class to the [dependency injection](../Dependency-Injection.md) system. So, you can inject and use it whenever you need:
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly DaprClient _daprClient;
|
||||
|
||||
public MyService(DaprClient daprClient)
|
||||
{
|
||||
_daprClient = daprClient;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
// TODO: Use the injected _daprClient object
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
Injecting `DaprClient` is the recommended way of using it in your application code. When you inject it, the `IAbpDaprClientFactory` service is used to create it, which is explained in the next section.
|
||||
|
||||
### IAbpDaprClientFactory
|
||||
|
||||
`IAbpDaprClientFactory` can be used to create `DaprClient` or `HttpClient` objects to perform operations on Dapr. It uses `AbpDaprOptions`, so you can configure the settings in a central place.
|
||||
|
||||
**Example usages:**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IAbpDaprClientFactory _daprClientFactory;
|
||||
|
||||
public MyService(IAbpDaprClientFactory daprClientFactory)
|
||||
{
|
||||
_daprClientFactory = daprClientFactory;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
// Create a DaprClient object with default options
|
||||
DaprClient daprClient = await _daprClientFactory.CreateAsync();
|
||||
|
||||
/* Create a DaprClient object with configuring
|
||||
* the DaprClientBuilder object */
|
||||
DaprClient daprClient2 = await _daprClientFactory
|
||||
.CreateAsync(builder =>
|
||||
{
|
||||
builder.UseDaprApiToken("...");
|
||||
});
|
||||
|
||||
// Create an HttpClient object
|
||||
HttpClient httpClient = await _daprClientFactory
|
||||
.CreateHttpClientAsync("target-app-id");
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`CreateHttpClientAsync` method also gets optional `daprEndpoint` and `daprApiToken` parameters.
|
||||
|
||||
> ABP uses `IAbpDaprClientFactory` when it needs to create a Dapr client. You can also use Dapr API to create client objects in your application. Using `IAbpDaprClientFactory` is recommended, but not required.
|
||||
|
||||
## C# API Client Proxies Integration
|
||||
|
||||
ABP can [dynamically](../API/Dynamic-CSharp-API-Clients.md) or [statically](../API/Static-CSharp-API-Clients.md) generate proxy classes to invoke your HTTP APIs from a Dotnet client application. It makes perfect sense to consume HTTP APIs in a distributed system. The [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) package configures the client-side proxies system, so it uses Dapr's service invocation building block for the communication between your applications.
|
||||
|
||||
### Installation
|
||||
|
||||
Use the ABP CLI to add the [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet package to your project (to the client side):
|
||||
|
||||
* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed before.
|
||||
* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.Http.Client.Dapr` package to.
|
||||
* Run the `abp add-package Volo.Abp.Http.Client.Dapr` command.
|
||||
|
||||
If you want to do it manually, install the [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet package to your project and add `[DependsOn(typeof(AbpHttpClientDaprModule))]` to the [ABP module](../Module-Development-Basics.md) class inside your project.
|
||||
|
||||
### Configuration
|
||||
|
||||
Once you install the [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet package, all you need to do is to configure ABP's remote services option either in `appsettings.json` or using the `AbpRemoteServiceOptions` [options class](../Options.md).
|
||||
|
||||
**Example:**
|
||||
|
||||
````csharp
|
||||
{
|
||||
"RemoteServices": {
|
||||
"Default": {
|
||||
"BaseUrl": "http://dapr-httpapi/"
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`dapr-httpapi` in this example is the application id of the server application in your Dapr configuration.
|
||||
|
||||
The remote service name (`Default` in this example) should match the remote service name specified in the `AddHttpClientProxies` call for dynamic client proxies or the `AddStaticHttpClientProxies` call for static client proxies. Using `Default` is fine if your client communicates to a single server. However, if your client uses multiple servers, you typically have multiple keys in the `RemoteServices` configuration. Once you configure the remote service endpoints as Dapr application ids, it will automatically work and make the HTTP calls through Dapr when you use ABP's client proxy system.
|
||||
|
||||
> See the [dynamic](../API/Dynamic-CSharp-API-Clients.md) and [static](../API/Static-CSharp-API-Clients.md) client proxy documents for details about the ABP's client proxy system.
|
||||
|
||||
## Distributed Event Bus Integration
|
||||
|
||||
[ABP's distributed event bus](../Distributed-Event-Bus.md) system provides a convenient abstraction to allow applications to communicate asynchronously via events. ABP has integration packages with various distributed messaging systems, like RabbitMQ, Kafka, and Azure. Dapr also has a [publish & subscribe building block](https://docs.dapr.io/developing-applications/building-blocks/pubsub/pubsub-overview/) for the same purpose: distributed messaging / events.
|
||||
|
||||
ABP's [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) and [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) packages make it possible to use the Dapr infrastructure for ABP's distributed event bus.
|
||||
|
||||
The [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) package can be used by any type of application (e.g., a Console or ASP.NET Core application) to publish events through Dapr. To be able to receive messages (by subscribing to events), you need to have the [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) package installed, and your application should be an ASP.NET Core application.
|
||||
|
||||
### Installation
|
||||
|
||||
If your application is an ASP.NET Core application and you want to send and receive events, you need to install the [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) package as described below:
|
||||
|
||||
* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed it before.
|
||||
* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.AspNetCore.Mvc.Dapr.EventBus` package to.
|
||||
* Run the `abp add-package Volo.Abp.AspNetCore.Mvc.Dapr.EventBus` command.
|
||||
|
||||
If you want to do it manually, install the [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) NuGet package to your project and add `[DependsOn(typeof(AbpAspNetCoreMvcDaprEventBusModule))]` to the [ABP module](../Module-Development-Basics.md) class inside your project.
|
||||
|
||||
> **If you install the [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) package, you don't need to install the [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) package, because the first one already has a reference to the latter one.**
|
||||
|
||||
If your application is not an ASP.NET Core application, you can't receive events from Dapr, at least with ABP's integration packages (see [Dapr's document](https://docs.dapr.io/developing-applications/building-blocks/pubsub/howto-publish-subscribe/) if you want to receive events in a different type of application). However, you can still publish messages using the [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) package. In this case, follow the steps below to install that package to your project:
|
||||
|
||||
* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed it before.
|
||||
* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.EventBus.Dapr` package to.
|
||||
* Run the `abp add-package Volo.Abp.EventBus.Dapr` command.
|
||||
|
||||
If you want to do it manually, install the [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) NuGet package to your project and add `[DependsOn(typeof(AbpEventBusDaprModule))]` to the [ABP module](../Module-Development-Basics.md) class inside your project.
|
||||
|
||||
### Configuration
|
||||
|
||||
You can configure the `AbpDaprEventBusOptions` [options class](../Options.md) for Dapr configuration:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprEventBusOptions>(options =>
|
||||
{
|
||||
options.PubSubName = "pubsub";
|
||||
});
|
||||
````
|
||||
|
||||
Available properties of the `AbpDaprEventBusOptions` class:
|
||||
|
||||
* `PubSubName` (optional): The `pubsubName` parameter while publishing messages through the `DaprClient.PublishEventAsync` method. Default value: `pubsub`.
|
||||
|
||||
### The ABP Subscription Endpoints
|
||||
|
||||
ABP provides the following endpoints to receive events from Dapr:
|
||||
|
||||
* `dapr/subscribe`: Dapr uses this endpoint to get a list of subscriptions from the application. ABP automatically returns all the subscriptions for your distributed event handler classes and custom controller actions with the `Topic` attribute.
|
||||
* `api/abp/dapr/event`: The unified endpoint to receive all the events from Dapr. ABP dispatches the events to your event handlers based on the topic name.
|
||||
|
||||
> **Since ABP provides the standard `dapr/subscribe` endpoint, you should not manually call the `app.MapSubscribeHandler()` method of Dapr.** You can use the `app.UseCloudEvents()` middleware in your ASP.NET Core pipeline if you want to support the [CloudEvents](https://cloudevents.io/) standard.
|
||||
|
||||
### Usage
|
||||
|
||||
#### The ABP Way
|
||||
|
||||
You can follow [ABP's distributed event bus documentation](../Distributed-Event-Bus.md) to learn how to publish and subscribe to events in the ABP way. No change required in your application code to use Dapr pub-sub. ABP will automatically subscribe to Dapr for your event handler classes (that implement the `IDistributedEventHandler` interface).
|
||||
|
||||
ABP provides `api/abp/dapr/event`
|
||||
|
||||
**Example: Publish an event using the `IDistributedEventBus` service**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IDistributedEventBus _distributedEventBus;
|
||||
|
||||
public MyService(IDistributedEventBus distributedEventBus)
|
||||
{
|
||||
_distributedEventBus = distributedEventBus;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
await _distributedEventBus.PublishAsync(new StockCountChangedEto
|
||||
{
|
||||
ProductCode = "AT837234",
|
||||
NewStockCount = 42
|
||||
});
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
**Example: Subscribe to an event by implementing the `IDistributedEventHandler` interface**
|
||||
|
||||
````csharp
|
||||
public class MyHandler :
|
||||
IDistributedEventHandler<StockCountChangedEto>,
|
||||
ITransientDependency
|
||||
{
|
||||
public async Task HandleEventAsync(StockCountChangedEto eventData)
|
||||
{
|
||||
var productCode = eventData.ProductCode;
|
||||
// ...
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
See [ABP's distributed event bus documentation](../Distributed-Event-Bus.md) to learn the details.
|
||||
|
||||
#### Using the Dapr API
|
||||
|
||||
In addition to ABP's standard distributed event bus system, you can also use Dapr's API to publish events.
|
||||
|
||||
> If you directly use the Dapr API to publish events, you may not benefit from ABP's standard distributed event bus features, like the outbox/inbox pattern implementation.
|
||||
|
||||
**Example: Publish an event using `DaprClient`**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly DaprClient _daprClient;
|
||||
|
||||
public MyService(DaprClient daprClient)
|
||||
{
|
||||
_daprClient = daprClient;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
await _daprClient.PublishEventAsync(
|
||||
"pubsub", // pubsub name
|
||||
"StockChanged", // topic name
|
||||
new StockCountChangedEto // event data
|
||||
{
|
||||
ProductCode = "AT837234",
|
||||
NewStockCount = 42
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
**Example: Subscribe to an event by creating an ASP.NET Core controller**
|
||||
|
||||
````csharp
|
||||
public class MyController : AbpController
|
||||
{
|
||||
[HttpPost("/stock-changed")]
|
||||
[Topic("pubsub", "StockChanged")]
|
||||
public async Task<IActionResult> TestRouteAsync(
|
||||
[FromBody] StockCountChangedEto model)
|
||||
{
|
||||
HttpContext.ValidateDaprAppApiToken();
|
||||
|
||||
// Do something with the event
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`HttpContext.ValidateDaprAppApiToken()` extension method is provided by ABP to check if the request is coming from Dapr. This is optional. You should configure Dapr to send the App API token to your application if you want to enable the validation. If not configured, `ValidateDaprAppApiToken()` does nothing. See [Dapr's App API Token document](https://docs.dapr.io/operations/security/app-api-token/) for more information. Also see the *AbpDaprOptions* and *Security* sections in this document.
|
||||
|
||||
See the [Dapr documentation](https://docs.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/publish-subscribe) to learn the details of sending & receiving events with the Dapr API.
|
||||
|
||||
## Distributed Lock
|
||||
|
||||
> Dapr's distributed lock feature is currently in the Alpha stage and may not be stable yet. It is not suggested to replace ABP's distributed lock with Dapr in that point.
|
||||
|
||||
ABP provides a [Distributed Locking](../Distributed-Locking.md) abstraction to control access to a shared resource by multiple applications. Dapr also has a [distributed lock building block](https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/). The [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr) package makes ABP use Dapr's distributed locking system.
|
||||
|
||||
### Installation
|
||||
|
||||
Use the ABP CLI to add the [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr) NuGet package to your project (to the client side):
|
||||
|
||||
* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed it before.
|
||||
* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.DistributedLocking.Dapr` package to.
|
||||
* Run the `abp add-package Volo.Abp.DistributedLocking.Dapr` command.
|
||||
|
||||
If you want to do it manually, install the [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr) NuGet package to your project and add `[DependsOn(typeof(AbpDistributedLockingDaprModule))]` to the [ABP module](../Module-Development-Basics.md) class inside your project.
|
||||
|
||||
### Configuration
|
||||
|
||||
You can use the `AbpDistributedLockDaprOptions` options class in the `ConfigureServices` method of [your module](../Module-Development-Basics.md) to configure the Dapr distributed lock:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDistributedLockDaprOptions>(options =>
|
||||
{
|
||||
options.StoreName = "mystore";
|
||||
});
|
||||
````
|
||||
|
||||
The following options are available:
|
||||
|
||||
* **`StoreName`** (required): The store name used by Dapr. Lock key names are scoped in the same store. That means different applications can acquire the same lock name in different stores. Use the same store name for the same resources you want to control the access of.
|
||||
* `Owner` (optional): The `owner` value used by the `DaprClient.Lock` method. If you don't specify, ABP uses a random value, which is fine in general.
|
||||
* `DefaultExpirationTimeout` (optional): Default value of the time after which the lock gets expired. Default value: 2 minutes.
|
||||
|
||||
### Usage
|
||||
|
||||
You can inject and use the `IAbpDistributedLock` service, just like explained in the [Distributed Locking document](../Distributed-Locking.md).
|
||||
|
||||
**Example:**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IAbpDistributedLock _distributedLock;
|
||||
|
||||
public MyService(IAbpDistributedLock distributedLock)
|
||||
{
|
||||
_distributedLock = distributedLock;
|
||||
}
|
||||
|
||||
public async Task MyMethodAsync()
|
||||
{
|
||||
await using (var handle =
|
||||
await _distributedLock.TryAcquireAsync("MyLockName"))
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
// your code that access the shared resource
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
There are two points we should mention about the `TryAcquireAsync` method, as different from ABP's standard usage:
|
||||
|
||||
* The `timeout` parameter is currently not used (even if you specify it), because Dapr doesn't support waiting to obtain the lock.
|
||||
* Dapr uses the expiration timeout system (that means the lock is automatically released after that timeout even if you don't release the lock by disposing the handler). However, ABP's `TryAcquireAsync` method has no such a parameter. Currently, you can set `AbpDistributedLockDaprOptions.DefaultExpirationTimeout` as a global value in your application.
|
||||
|
||||
As mentioned first, Dapr's distributed lock feature is currently in the Alpha stage and its API is a candidate to change. You should use it as is if you want, but be ready for the changes in the future. For now, we are recommending to use the [DistributedLock](https://github.com/madelson/DistributedLock) library as explained in ABP's [Distributed Locking document](../Distributed-Locking.md).
|
||||
|
||||
## Security
|
||||
|
||||
If you are using Dapr, most or all the incoming and outgoing requests in your application pass through Dapr. Dapr uses two kinds of API tokens to secure the communication between your application and Dapr.
|
||||
|
||||
### Dapr API Token
|
||||
|
||||
> This token is automatically set by default and generally you don't care about it.
|
||||
|
||||
The [Enable API token authentication in Dapr](https://docs.dapr.io/operations/security/api-token/) document describes what the Dapr API token is and how it is configured. Please read that document if you want to enable it for your application.
|
||||
|
||||
If you enable the Dapr API token, you should send that token in every request to Dapr from your application. `AbpDaprOptions` defines a `DaprApiToken` property as a central point to configure the Dapr API token in your application.
|
||||
|
||||
The default value of the `DaprApiToken` property is set from the `DAPR_API_TOKEN` environment variable and that environment variable is set by Dapr when it runs. So, most of the time, you don't need to configure `AbpDaprOptions.DaprApiToken` in your application. However, if you need to configure (or override) it, you can do in the `ConfigureServices` method of your module class as shown in the following code block:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
options.DaprApiToken = "...";
|
||||
});
|
||||
````
|
||||
|
||||
Or you can set it in your `appsettings.json` file:
|
||||
|
||||
````json
|
||||
"Dapr": {
|
||||
"DaprApiToken": "..."
|
||||
}
|
||||
````
|
||||
|
||||
Once you set it, it is used when you inject `DaprClient` or use `IAbpDaprClientFactory`. If you need that value in your application, you can inject `IDaprApiTokenProvider` and use its `GetDaprApiToken()` method.
|
||||
|
||||
### App API Token
|
||||
|
||||
> Enabling App API token validation is strongly recommended. Otherwise, for example, any client can directly call your event subscription endpoint, and your application acts like an event has occurred (if there is no other security policy in your event subscription endpoint).
|
||||
|
||||
The [Authenticate requests from Dapr using token authentication](https://docs.dapr.io/operations/security/app-api-token/) document describes what the App API token is and how it is configured. Please read that document if you want to enable it for your application.
|
||||
|
||||
If you enable the App API token, you can validate it to ensure that the request is coming from Dapr. ABP provides useful shortcuts to validate it.
|
||||
|
||||
**Example: Validate the App API token in an event handling HTTP API**
|
||||
|
||||
````csharp
|
||||
public class MyController : AbpController
|
||||
{
|
||||
[HttpPost("/stock-changed")]
|
||||
[Topic("pubsub", "StockChanged")]
|
||||
public async Task<IActionResult> TestRouteAsync(
|
||||
[FromBody] StockCountChangedEto model)
|
||||
{
|
||||
// Validate the App API token!
|
||||
HttpContext.ValidateDaprAppApiToken();
|
||||
|
||||
// Do something with the event
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`HttpContext.ValidateDaprAppApiToken()` is an extension method provided by the ABP Framework. It throws an `AbpAuthorizationException` if the token was missing or wrong in the HTTP header (the header name is `dapr-api-token`). You can also inject `IDaprAppApiTokenValidator` and use its methods to validate the token in any service (not only in a controller class).
|
||||
|
||||
You can configure `AbpDaprOptions.AppApiToken` if you want to set (or override) the App API token value. The default value is set by the `APP_API_TOKEN` environment variable. You can change it in the `ConfigureServices` method of your module class as shown in the following code block:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
options.AppApiToken = "...";
|
||||
});
|
||||
````
|
||||
|
||||
Or you can set it in your `appsettings.json` file:
|
||||
|
||||
````json
|
||||
"Dapr": {
|
||||
"AppApiToken": "..."
|
||||
}
|
||||
````
|
||||
|
||||
If you need that value in your application, you can inject `IDaprApiTokenProvider` and use its `GetAppApiToken()` method.
|
||||
|
||||
## See Also
|
||||
|
||||
* [Dapr for .NET Developers](https://docs.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/)
|
||||
* [The Official Dapr Documentation](https://docs.dapr.io/)
|
||||
@ -0,0 +1,452 @@
|
||||
# Deploying ABP Project to Azure App Service
|
||||
|
||||
In this document, you will learn how to create and deploy your first ABP web app to [Azure App Service](https://docs.microsoft.com/en-us/azure/app-service/overview). The App Service supports various versions of .NET apps, and provides a highly scalable, self-patching web hosting service. ABP web apps are cross-platform and can be hosted on Linux, Windows or MacOS.
|
||||
|
||||
****Prerequisites****
|
||||
|
||||
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/dotnet).
|
||||
- A GitHub account [Create an account for free](http://github.com/).
|
||||
|
||||
|
||||
|
||||
## Creating a new ABP application
|
||||
|
||||
Create a repository on [GitHub.com](https://github.com/) (keep all settings as default).
|
||||
|
||||
Open the command prompt and clone the repository into a folder on your computer
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-username/your-repository-name.git
|
||||
```
|
||||
|
||||
Check your dotnet version. It should be at least 3.1.x
|
||||
|
||||
```bash
|
||||
dotnet --version
|
||||
```
|
||||
|
||||
Install or update the [ABP CLI](https://docs.abp.io/en/abp/latest/cli) with the following command:
|
||||
|
||||
```bash
|
||||
dotnet tool install -g Volo.Abp.Cli || dotnet tool update -g Volo.Abp.Cli
|
||||
```
|
||||
|
||||
Open the command prompt in the *GitHub repository folder* and create a new ABP Blazor solution with the command below:
|
||||
|
||||
```bash
|
||||
abp new YourAppName -u blazor
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Running the application
|
||||
|
||||
Open the command prompt in the *[YourAppName].DbMigrator* project and enter the command below to apply the database migrations:
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Open the command prompt in the *[YourAppName].HttpApi.Host* project to run the API project:
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Navigate to the *applicationUrl* specified in *the launchSettings.json* file of the *[YourAppName].HttpApi.Host project*. You should get the *Swagger window*
|
||||
|
||||
Open the command prompt in the *[YourAppName].Blazor* folder and enter the command below to run the Blazor project:
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Navigate to the *applicationUrl* specified in the *launchSettings.json* file of the *[YourAppName].Blazor* project and you should see the landing page.
|
||||
|
||||
Stop both the *API* and the *Blazor* project by pressing **CTRL+C**
|
||||
|
||||
|
||||
|
||||
## Committing to GitHub
|
||||
|
||||
Before the GitHub commit, you have to delete the line "**/wwwroot/libs/*" at *.gitignore* file.
|
||||
|
||||

|
||||
|
||||
Open the command prompt in the root folder of your project and *add, commit and push* all your changes to your GitHub repository:
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m initialcommit
|
||||
git push
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Configuring Azure database connection string
|
||||
|
||||
Create a SQL database on Azure and change the connection string in all the *appsettings.json* files.
|
||||
|
||||
* Login into [Azure Portal](https://portal.azure.com/)
|
||||
|
||||
* Click **Create a resource**
|
||||
|
||||
* Search for *SQL Database*
|
||||
|
||||
* Click the **Create** button in the *SQL Database window*
|
||||
|
||||
* Create a new resource group. Name it *rg[YourAppName]*
|
||||
|
||||
* Enter *[YourAppName]Db* as database name
|
||||
|
||||
* Create a new Server and name it *[yourappname]server*
|
||||
|
||||
* Enter a serveradmin login and passwords. Click the **OK** button
|
||||
|
||||
* Select your *Location*
|
||||
|
||||
* Check *Allow Azure services to access server*
|
||||
|
||||
* Click **Configure database**. Go to the *Basic* version and click the **Apply** button
|
||||
|
||||
* Click the **Review + create** button. Click **Create**
|
||||
|
||||
* Click **Go to resource** and click **SQL server** when the SQL Database is created
|
||||
|
||||
* Click **Networking** under Security left side menu
|
||||
|
||||
* Select **Selected networks** and click **Add your client IP$ address** at the Firewall rules
|
||||
|
||||
* Select **Allow Azure and resources to access this seerver** and save
|
||||
|
||||
* Go to your **SQL database**, click **Connection strings** and copy the connection string
|
||||
|
||||
* Copy/paste the *appsettings.json* files of the *[YourAppName].HttpApi.Host* and the *[YourAppName].DbMigrator* project
|
||||
|
||||
* Do not forget to replace {your_password} with the correct server password you entered in Azure SQL Database
|
||||
|
||||
|
||||
|
||||
## Running DB Migrations
|
||||
|
||||
Open the command prompt in the *[YourAppName].DbMigrator* project again and enter the command below to apply the database migrations:
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Open the command prompt in the *[YourAppName].HttpApi.Host* project and enter the command below to check your API is working:
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Stop the *[YourAppName].HttpApi.Host* by pressing CTRL+C.
|
||||
|
||||
|
||||
|
||||
## Committing to GitHub
|
||||
|
||||
Open the command prompt in the root folder of your project and add, commit and push all your changes to your GitHub repository
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m initialcommit
|
||||
git push
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Setting up the Build pipeline in AzureDevops and publish the Build Artifacts
|
||||
|
||||
* Sign in Azure DevOps
|
||||
|
||||
* Click **New organization** and follow the steps to create a new organisation. Name it [YourAppName]org
|
||||
|
||||
* Enter [YourAppName]Proj as project name in the ***Create a project to get started*** window
|
||||
|
||||
* Select **Public visibility** and click the **Create project** button
|
||||
|
||||
* Click the **Pipelines** button to continue
|
||||
|
||||
* Click the **Create Pipeline** button
|
||||
|
||||
Select GitHub in the Select your repository window
|
||||
|
||||

|
||||
|
||||
* Enter the Connection name. *[YourAppName]GitHubConnection* and click **Authorize using OAuth**
|
||||
|
||||
* Select your **GitHub** [YourAppName]repo and click Continue
|
||||
|
||||
* Search for **ASP.NET** in the ***Select a template*** window
|
||||
|
||||

|
||||
|
||||
* Select the ASP.NET Core template and click the **Apply** button
|
||||
|
||||
* Add the below commands block as a first step in the pipeline
|
||||
|
||||
```
|
||||
- task: UseDotNet@2
|
||||
inputs:
|
||||
packageType: 'sdk'
|
||||
version: '6.0.106'
|
||||
```
|
||||
|
||||

|
||||
|
||||
* Select **Settings** on the second task(Nugetcommand@2) in the pipeline
|
||||
|
||||
* Select **Feeds in my Nuget.config** and type **Nuget.config** in the text box
|
||||
|
||||

|
||||
|
||||
* Add the below commands block to the end of the pipeline
|
||||
|
||||
```
|
||||
- task: PublishBuildArtifacts@1
|
||||
displayName: 'Publish Artifact'
|
||||
inputs:
|
||||
PathtoPublish: '$(build.artifactstagingdirectory)'
|
||||
ArtifactName: '$(Parameters.ArtifactName)'
|
||||
condition: succeededOrFailed()
|
||||
```
|
||||
|
||||

|
||||
|
||||
```
|
||||
# ASP.NET
|
||||
# Build and test ASP.NET projects.
|
||||
# Add steps that publish symbols, save build artifacts, deploy, and more:
|
||||
# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4
|
||||
|
||||
trigger:
|
||||
- main
|
||||
|
||||
pool:
|
||||
vmImage: 'windows-latest'
|
||||
|
||||
variables:
|
||||
solution: '**/*.sln'
|
||||
buildPlatform: 'Any CPU'
|
||||
buildConfiguration: 'Release'
|
||||
|
||||
steps:
|
||||
- task: UseDotNet@2
|
||||
inputs:
|
||||
packageType: 'sdk'
|
||||
version: '6.0.106'
|
||||
|
||||
- task: NuGetToolInstaller@1
|
||||
|
||||
- task: NuGetCommand@2
|
||||
inputs:
|
||||
command: 'restore'
|
||||
restoreSolution: '$(solution)'
|
||||
feedsToUse: 'config'
|
||||
nugetConfigPath: 'NuGet.config'
|
||||
|
||||
- task: VSBuild@1
|
||||
inputs:
|
||||
solution: '$(solution)'
|
||||
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
|
||||
platform: '$(buildPlatform)'
|
||||
configuration: '$(buildConfiguration)'
|
||||
|
||||
- task: VSTest@2
|
||||
inputs:
|
||||
platform: '$(buildPlatform)'
|
||||
configuration: '$(buildConfiguration)'
|
||||
|
||||
- task: PublishBuildArtifacts@1
|
||||
displayName: 'Publish Artifact'
|
||||
inputs:
|
||||
PathtoPublish: '$(build.artifactstagingdirectory)'
|
||||
ArtifactName: '$(Parameters.ArtifactName)'
|
||||
publishLocation: 'Container'
|
||||
condition: succeededOrFailed()
|
||||
```
|
||||
|
||||
* Click **Save & queue** in the top menu. Click **Save & queue** again and click **Save and run** to run the Build pipeline
|
||||
|
||||
* When the Build pipeline has finished. Click **1 published; 1 consumed**
|
||||
|
||||
|
||||
|
||||
## Creating a Web App in the Azure Portal to deploy [YourAppName].HttpApi.Host project
|
||||
|
||||
* Search for Web App in the *Search the Marketplace* field
|
||||
|
||||
* Click the **Create** button in the Web App window
|
||||
|
||||
* Select rg[YourAppName] in the *Resource Group* dropdown
|
||||
|
||||
* Enter [YourAppName]API in the *Name input* field
|
||||
|
||||
* Select code, .NET Core 3.1 (LTS) and windows as *Operating System*
|
||||
|
||||
* Enter [YourAppName]API in the *Name input* field
|
||||
|
||||
* Select .NET Core 3.1 (LTS) in the *Runtime stack* dropdown
|
||||
|
||||
* Select Windows as *Operating System*
|
||||
|
||||
* Select the same *Region* as in the SQL server you created in Part 3
|
||||
|
||||

|
||||
|
||||
* Click **Create new** in the Windows Plan. Name it [YourAppName]ApiWinPlan
|
||||
|
||||
* Click **Change size** in Sku and size. Go to the Dev/Test Free F1 version and click the **Apply** button
|
||||
|
||||

|
||||
|
||||
* Click the **Review + create** button. Click the **Create** button
|
||||
|
||||
* Click **Go to resource** when the Web App has been created
|
||||
|
||||
|
||||
|
||||
## Creating a release pipeline in the AzureDevops and deploy [YourAppName].HttpApi.Host project
|
||||
|
||||
* Sign in into [Azure DevOps](https://azure.microsoft.com/en-us/services/devops/)
|
||||
|
||||
* Click [YourAppName]Proj and click **Releases** in the *Pipelines* menu
|
||||
|
||||
* Click the **New pipeline** button in the *No release pipelines found* window
|
||||
|
||||
* Select *Azure App Service deployment* and click the **Apply** button
|
||||
|
||||

|
||||
|
||||
* Enter *[YourAppName]staging* in the *Stage name* field in the *Stage* window. And close the window
|
||||
|
||||
* Click **+ Add an artifact** in the *Pipeline* tab
|
||||
|
||||
* Select the **Build** icon as *Source type* in the *Add an artifact* window
|
||||
|
||||
* Select Build pipeline in the *Source (build pipeline)* dropdown and click the **Add** button
|
||||
|
||||

|
||||
|
||||
* Click the **Continuous deployment trigger (thunderbolt icon)**
|
||||
|
||||
* Set the toggle to **Enabled** in the the *Continuous deployment trigger* window
|
||||
|
||||
* Click **+ Add** in *No filters added*. Select **Include** in the *Type* dropdown. Select your branch in the *Build branch* dropdown and close the window
|
||||
|
||||

|
||||
|
||||
* Click **the little red circle with the exclamation mark** in the *Tasks* tab menu
|
||||
|
||||
* Select your subscription in the *Azure subscription* dropdown.
|
||||
|
||||

|
||||
|
||||
* Click **Authorize** and enter your credentials in the next screens
|
||||
|
||||
* After Authorization, select the **[YourAppName]API** in the *App service name* dropdown
|
||||
|
||||
* Click the **Deploy Azure App Service** task
|
||||
|
||||
* Select **[YourAppName].HttpApi.Host.zip** in the *Package or folder* input field
|
||||
|
||||

|
||||
|
||||
* Click the **Save** icon in the top menu and click **OK**
|
||||
|
||||
* Click **Create release** in the top menu. Click **Create** to create a release
|
||||
|
||||
* Click the *Pipeline* tab and wait until the Deployment succeeds
|
||||
|
||||

|
||||
|
||||
* Open a browser and navigate to the URL of your Web App
|
||||
|
||||
```
|
||||
https://[YourAppName]api.azurewebsites.net
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
## Creating a Web App in Azure Portal to deploy [YourAppName].Blazor project
|
||||
|
||||
* Login into [Azure Portal](https://portal.azure.com/)
|
||||
|
||||
* Click **Create a resource**
|
||||
|
||||
* Search for *Web App* in the *Search the Marketplace* field
|
||||
|
||||
* Click the **Create** button in the *Web App* window
|
||||
|
||||
* Select *rg[YourAppName]* in the *Resource Group* dropdown
|
||||
|
||||
* Enter *[YourAppName]Blazor* in the *Name* input field
|
||||
|
||||
* Select *.NET Core 3.1 (LTS)* in the *Runtime stack* dropdown
|
||||
|
||||
* Select *Windows* as *Operating System*
|
||||
|
||||
* Select the same region as the SQL server you created in Part 3
|
||||
|
||||
* Select the [YourAppName]ApiWinPlan in the *Windows Plan* dropdown
|
||||
|
||||

|
||||
|
||||
* Click the **Review + create** button. Click **Create** button
|
||||
|
||||
* Click **Go to resource** when the Web App has been created
|
||||
|
||||
* Copy the URL of the Blazor Web App for later use
|
||||
|
||||
```
|
||||
https://[YourAppName]blazor.azurewebsites.net
|
||||
```
|
||||
|
||||
|
||||
## Changing the Web App configuration for the Azure App Service
|
||||
|
||||
Copy the URL of the Api Host and Blazor Web App. Change appsettings.json files in the Web App as follows images.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
## Adding an extra Stage in the Release pipeline in the AzureDevops to deploy [YourAppName].Blazor project
|
||||
|
||||
* Go to the *Release* pipeline in [Azure DevOps](https://azure.microsoft.com/en-us/services/devops/) and click **Edit**
|
||||
|
||||
* Click the **+ Add** link and add a **New Stage**
|
||||
|
||||

|
||||
|
||||
* Select *Azure App Service deployment* and click the **Apply** button
|
||||
|
||||
* Enter *BlazorDeployment* in the *Stage name* input field and close the *Stage* window
|
||||
|
||||
* Click the **little red circle with the exclamation mark** in the BlazorDeployment stage
|
||||
|
||||
* Select your subscription in the *Azure subscription* dropdown
|
||||
|
||||
* Select your Blazor Web App in the *App service name* dropdown
|
||||
|
||||
* Click the **Deploy Azure App Service task**
|
||||
|
||||
* Select *[YourAppName].Blazor.zip* in the *Package or folder* input field
|
||||
|
||||

|
||||
|
||||
* Click **Save** in the top menu and click the **OK** button after
|
||||
|
||||
* Click **Create release** in the top menu and click the **Create** button
|
||||
|
||||

|
||||
|
||||

|
||||
@ -0,0 +1,125 @@
|
||||
# Blazor UI: Layout Hooks
|
||||
|
||||
ABP Framework theming system places the page layout into the [theme](Theming.md) NuGet packages. That means the final application doesn't include a layout, so you can't directly change the layout code to customize it.
|
||||
|
||||
> If you create a Blazor WASM project, the `index.html` file will be included within the template. You can also customize it to your needs.
|
||||
|
||||
You can copy the theme code into your solution. In this case, you are completely free to customize it. However, then you won't be able to get automatic updates of the theme (by upgrading the theme NuGet package).
|
||||
|
||||
The **Layout Hook System** allows you to **add code** at some specific parts of the layout. All layouts of all themes should implement these hooks. Finally, you can add a **razor component** into a hook point.
|
||||
|
||||
## Example: Add a Simple Announcement Alert
|
||||
|
||||
Assume that you need to add a simple banner to the layout (that will be available for all the pages) to make an announcement about your new product. First, **create a razor component** in your project:
|
||||
|
||||

|
||||
|
||||
**AnnouncementComponent.razor.cs**
|
||||
|
||||
```csharp
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace Acme.BookStore.Blazor.Components;
|
||||
|
||||
public partial class AnnouncementComponent : ComponentBase
|
||||
{
|
||||
private const string AnnouncementLocalStorageKey = "product-announcement-status";
|
||||
|
||||
[Inject]
|
||||
public IJSRuntime JsRuntime { get; set; }
|
||||
|
||||
public bool ShowBanner { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
ShowBanner = await ShowAnnouncementBannerAsync();
|
||||
}
|
||||
|
||||
private async Task<bool> ShowAnnouncementBannerAsync()
|
||||
{
|
||||
var announcementLocalStorageValue = await JsRuntime.InvokeAsync<string>("localStorage.getItem", AnnouncementLocalStorageKey);
|
||||
|
||||
return announcementLocalStorageValue != null &&
|
||||
bool.TryParse(announcementLocalStorageValue, out var showAnnouncementBanner) && showAnnouncementBanner;
|
||||
}
|
||||
|
||||
private async Task HideAnnouncementBannerAsync()
|
||||
{
|
||||
await JsRuntime.InvokeVoidAsync("localStorage.setItem", AnnouncementLocalStorageKey, true);
|
||||
ShowBanner = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**AnnouncementComponent.razor**
|
||||
|
||||
```html
|
||||
@if(ShowBanner)
|
||||
{
|
||||
<div class="alert alert-info">
|
||||
A brand new product is in sale. Click <a href="#">here</a> to learn more.
|
||||
<button @onclick="async () => { await HideAnnouncementBannerAsync(); }">Hide</button>
|
||||
</div>
|
||||
}
|
||||
```
|
||||
|
||||
Then, you can add this component to any of the hook points in the `ConfigureServices` of your module class:
|
||||
|
||||
```csharp
|
||||
Configure<AbpLayoutHookOptions>(options =>
|
||||
{
|
||||
options.Add(
|
||||
LayoutHooks.Body.Last, //The hook name
|
||||
typeof(AnnouncementComponent) //The component to add
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
Now, the `AnnouncementComponent` will be rendered in the `body` of the page as the last item.
|
||||
|
||||
### Specifying the Layout
|
||||
|
||||
The configuration above adds the `AnnouncementComponent` to all layouts. You may want to only add it to a specific layout:
|
||||
|
||||
````csharp
|
||||
Configure<AbpLayoutHookOptions>(options =>
|
||||
{
|
||||
options.Add(
|
||||
LayoutHooks.Body.Last,
|
||||
typeof(AnnouncementComponent),
|
||||
layout: StandardLayouts.Application //Set the layout to add
|
||||
);
|
||||
});
|
||||
````
|
||||
|
||||
See the *Layouts* section below to learn more about the layout system.
|
||||
|
||||
## Layout Hook Points
|
||||
|
||||
There are some pre-defined layout hook points. The standard hook points are:
|
||||
|
||||
* `LayoutHooks.Body.First`: Used to add a component as the first item in the HTML body tag.
|
||||
* `LayoutHooks.Body.Last`: Used to add a component as the last item in the HTML body tag.
|
||||
|
||||
> You (or the modules you are using) can add **multiple items to the same hook point**. All of them will be added to the layout in the order they were added.
|
||||
|
||||
## Layouts
|
||||
|
||||
The layout system allows themes to define the standard named layouts and allows any page to select a proper layout for its purpose. There is one pre-defined layout:
|
||||
|
||||
* "**Application**": The main (and the default) layout for an application. It typically contains a header, menu (sidebar), footer, toolbar... etc.
|
||||
|
||||
This layout is defined in the `StandardLayouts` class as constants. You can definitely create your own layouts, but this layout is the standard layout and it's implemented by all the themes out of the box.
|
||||
|
||||
> If you don't specify the layout, your razor component will be rendered in all of the layouts.
|
||||
|
||||
### Layout Location
|
||||
|
||||
You can find the `MainLayout.razor` [here](https://github.com/abpframework/abp/blob/dev/modules/basic-theme/src/Volo.Abp.AspNetCore.Components.Web.BasicTheme/Themes/Basic/MainLayout.razor) for the basic theme. You can take it as a reference to build your own layouts or you can override it, if necessary.
|
||||
|
||||
## See Also
|
||||
|
||||
* [Customization / Overriding Components](Customization-Overriding-Components.md)
|
||||
|
After Width: | Height: | Size: 12 KiB |
@ -0,0 +1,140 @@
|
||||
# Empezando con ABP y una Aplicacion AspNet Core MVC Web
|
||||
|
||||
Este tutorial explica como empezar una aplicacion ABP desde cero usando las dependencias minimas. Uno generalmente desea
|
||||
empezar con la **[plantilla de inicio](Getting-Started-AspNetCore-MVC-Template.md)**.
|
||||
|
||||
## Crea un Proyecto Nuevo
|
||||
|
||||
1. Crea una Aplicacion Web AspNet Core nueva usando Visual Studio 2022 (17.0.0+):
|
||||
|
||||

|
||||
|
||||
2. Configura el nuevo proyecto:
|
||||
|
||||

|
||||
|
||||
3. Presione el boton Create:
|
||||
|
||||

|
||||
|
||||
## Instale el paquete Volo.Abp.AspNetCore.Mvc
|
||||
|
||||
Volo.Abp.AspNetCore.Mvc es el paquete de integracion con AspNet Core MVC para ABP. Siendo asi, instalalo en su proyecto:
|
||||
|
||||
````
|
||||
Install-Package Volo.Abp.AspNetCore.Mvc
|
||||
````
|
||||
|
||||
## Crea el primer modulo ABP
|
||||
|
||||
ABP es un marco de referencia modular y require una clase de **inicio (raíz) tipo modulo** derivada de ``AbpModule``:
|
||||
|
||||
````C#
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Volo.Abp;
|
||||
using Volo.Abp.AspNetCore.Mvc;
|
||||
using Volo.Abp.Modularity;
|
||||
|
||||
namespace BasicAspNetCoreApplication
|
||||
{
|
||||
[DependsOn(typeof(AbpAspNetCoreMvcModule))]
|
||||
public class AppModule : AbpModule
|
||||
{
|
||||
public override void OnApplicationInitialization(ApplicationInitializationContext context)
|
||||
{
|
||||
var app = context.GetApplicationBuilder();
|
||||
var env = context.GetEnvironment();
|
||||
|
||||
// Configura la canalización de peticiones HTTP.
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
// El valor por defecto de HSTS es 30 dias. Debes cambiar esto en ambientes productivos. Referencia https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseStaticFiles();
|
||||
app.UseRouting();
|
||||
app.UseConfiguredEndpoints();
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
``AppModule`` es un buen nombre para el modulo de inicio de una aplicacion.
|
||||
|
||||
Los paquetes de ABP definen clases de tipo modulo y cada modulo puede depender de otro.
|
||||
En el codigo anterior, el ``AppModule`` depende de el modulo ``AbpAspNetCoreMvcModule`` (definido por el paquete [Volo.Abp.AspNetCore.Mvc](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc)). Es comun agregar el atributo ``DependsOn`` despues de instalar un paquete ABP nuevo.
|
||||
|
||||
En vez de la clase de inicion Startup, estamos configurando una canalizacion de ASP.NET Core en este modulo.
|
||||
|
||||
## La clase Program
|
||||
|
||||
El proximo paso es modificar la clase Program para integrate el sistema de modulos ABP:
|
||||
|
||||
````C#
|
||||
using BasicAspNetCoreApplication;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
await builder.Services.AddApplicationAsync<AppModule>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
await app.InitializeApplicationAsync();
|
||||
await app.RunAsync();
|
||||
````
|
||||
|
||||
``builder.Services.AddApplicationAsync<AppModule>();`` Agrega todos los servicios definidos en todos los modulos empezando desde ``AppModule``.
|
||||
|
||||
``app.InitializeApplicationAsync()`` inicializa y empieza la aplicacion.
|
||||
|
||||
## Ejecutar la Aplicación
|
||||
|
||||
Es todo! Ejecuta la aplicación, debe funcionar como esperado.
|
||||
|
||||
## Uso de Autofac como Marco de Inyección de Dependencia
|
||||
|
||||
Mientras el sistema de Inyección de Dependencia de ASP.NET Core es suficiente para requerimientos basico, [Autofac](https://autofac.org/) proporciona características avanzadas como Inyección de Propiedades e Intercepcion de Metodos, los cuales son necesarios para que ABP pueda llevar a cabo funciones avanzadas.
|
||||
|
||||
El acto de remplazar el sistema DI de ASP.NET Core por Autofac e integrarlo con ABP es facil.
|
||||
|
||||
1. Instala el paquete [Volo.Abp.Autofac](https://www.nuget.org/packages/Volo.Abp.Autofac)
|
||||
|
||||
````
|
||||
Install-Package Volo.Abp.Autofac
|
||||
````
|
||||
|
||||
2. Agrega la dependencia sobre el modulo ``AbpAutofacModule``
|
||||
|
||||
````C#
|
||||
[DependsOn(typeof(AbpAspNetCoreMvcModule))]
|
||||
[DependsOn(typeof(AbpAutofacModule))] //Agrega la dependencia sobre el modulo ABP Autofac
|
||||
public class AppModule : AbpModule
|
||||
{
|
||||
...
|
||||
}
|
||||
````
|
||||
|
||||
3. Actualiza `Program.cs` para que use Autofac:
|
||||
|
||||
````C#
|
||||
using BasicAspNetCoreApplication;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Host.UseAutofac(); //Agrega esta linea
|
||||
|
||||
await builder.Services.AddApplicationAsync<AppModule>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
await app.InitializeApplicationAsync();
|
||||
await app.RunAsync();
|
||||
````
|
||||
|
||||
## Codigo fuente
|
||||
|
||||
Obten el codigo fuente del ejemplo creado en este tutorial de [aqui](https://github.com/abpframework/abp-samples/tree/master/BasicAspNetCoreApplication).
|
||||
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 64 KiB |
@ -1,3 +1,182 @@
|
||||
## Validation
|
||||
# Validação
|
||||
|
||||
Façam
|
||||
O sistema de validação é utilizado para validar a entrada do usuário ou a requisição do cliente para uma ação de um controller ou por um serviço.
|
||||
|
||||
O ABP é compatível com o sistema de Validação de Modelos do ASP.NET Core e tudo escrito na [sua documentação](https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation) é válido para aplicações baseadas no ABP. Logo, esse documento foca nas funcionalidades do ABP ao invés de repetir a documentação da Microsoft.
|
||||
|
||||
Além disso, o ABP adiciona os seguintes benefícios:
|
||||
|
||||
* Define `IValidationEnabled` para adicionar validação automática para uma classe qualquer. Como todos os [serviços de aplicação](Application-Services.md) já o implementam, eles também são validados automaticamente.
|
||||
* Automaticamente traduz os erros de validação para os atributos de anotação de dados.
|
||||
* Provê serviços extensíveis para validar a chamada de um método ou o estado de um objeto.
|
||||
* Provê integração com o [FluentValidation](https://fluentvalidation.net/)
|
||||
|
||||
## Validando DTOs
|
||||
|
||||
Essa seção introduz brevemente o sistema de validação. Para mais detalhes, veja a [Documentação da Validação de Modelo em ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation).
|
||||
|
||||
### Atributos de anotação de dados
|
||||
|
||||
Utilizar anotações de dados é uma maneira simples de implementar uma validação formal para um [DTO](Data-Transfer-Objects.md) de uma forma declarativa. Exemplo:
|
||||
|
||||
````csharp
|
||||
public class CreateBookDto
|
||||
{
|
||||
[Required]
|
||||
[StringLength(100)]
|
||||
public string Name { get; set; }
|
||||
|
||||
[Required]
|
||||
[StringLength(1000)]
|
||||
public string Description { get; set; }
|
||||
|
||||
[Range(0, 999.99)]
|
||||
public decimal Price { get; set; }
|
||||
}
|
||||
````
|
||||
Quando você utilizar essa classe como parâmetro para um [serviço da aplicação](Application-Services.md) ou um controller, ele será automaticamente validado e a validação traduzida será lançada ([e tratada](Exception-Handling.md) pelo ABP framework).
|
||||
|
||||
### IValidatableObject
|
||||
|
||||
`IValidatableObject` pode ser implementado por um DTO para executar uma lógica customizada de validação. O `CreateBookDto` no exemplo a seguir implementa essa interface e verifica se o `Name` é igual a `Description` e retorna um erro de validação nesse caso.
|
||||
|
||||
````csharp
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Acme.BookStore
|
||||
{
|
||||
public class CreateBookDto : IValidatableObject
|
||||
{
|
||||
[Required]
|
||||
[StringLength(100)]
|
||||
public string Name { get; set; }
|
||||
|
||||
[Required]
|
||||
[StringLength(1000)]
|
||||
public string Description { get; set; }
|
||||
|
||||
[Range(0, 999.99)]
|
||||
public decimal Price { get; set; }
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(
|
||||
ValidationContext validationContext)
|
||||
{
|
||||
if (Name == Description)
|
||||
{
|
||||
yield return new ValidationResult(
|
||||
"Name and Description can not be the same!",
|
||||
new[] { "Name", "Description" }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
#### Resolvendo um serviço.
|
||||
|
||||
Se você precisar resolver um serviço do [sistema de injeção de dependências](Dependency-Injection.md), você pode utilizar o objeto `ValidationContext`.
|
||||
|
||||
````csharp
|
||||
var myService = validationContext.GetRequiredService<IMyService>();
|
||||
````
|
||||
|
||||
> Enquanto resolver os serviços no método `Validate` permite várias possibilidades, não é um boa prática implementar sua lógica de validação do domínio nos DTOs. Mantenha os DTOs simples. Seu propósito é transferir dados (DTO: Data Transfer Object, ou Objeto de Transferência de Dados).
|
||||
|
||||
## Infraestrutura de Validação.
|
||||
|
||||
Essa seção explica alguns serviços adicionais fornecidos pelo ABP Framework.
|
||||
|
||||
### Interface IValidationEnabled
|
||||
|
||||
`IValidationEnabled` é um marcador vazio de interface que pode ser implementado por qualquer classe (registrada e resolvida a partir do [DI](Dependency-Injection.md)) para permitir que o ABP framework realize o sistema de validação para os métodos da classe. Por exemplo:
|
||||
|
||||
````csharp
|
||||
using System.Threading.Tasks;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Volo.Abp.Validation;
|
||||
|
||||
namespace Acme.BookStore
|
||||
{
|
||||
public class MyService : ITransientDependency, IValidationEnabled
|
||||
{
|
||||
public virtual async Task DoItAsync(MyInput input)
|
||||
{
|
||||
//...
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
> O ABP framework utiliza o sistema de [Proxying Dinâmico / Interceptadores](Dynamic-Proxying-Interceptors.md) para realizar a validação. Para fazê-lo funcionar, seu método deve ser **virtual** ou seu serviço deve ser injetado e utilizado através de uma **interface** (como `IMyService`).
|
||||
|
||||
#### Habilitando e Desabilitando Validações
|
||||
|
||||
Você pode utilizar o `[DisableValidation]` e desabilitar a validação para métodos, classes e propriedades.
|
||||
|
||||
````csharp
|
||||
[DisableValidation]
|
||||
public Void MyMethod()
|
||||
{
|
||||
}
|
||||
|
||||
[DisableValidation]
|
||||
public class InputClass
|
||||
{
|
||||
public string MyProperty { get; set; }
|
||||
}
|
||||
|
||||
public class InputClass
|
||||
{
|
||||
[DisableValidation]
|
||||
public string MyProperty { get; set; }
|
||||
}
|
||||
````
|
||||
|
||||
### AbpValidationException
|
||||
|
||||
Uma vez que o ABP determina um erro de validação, é lançada uma validação do tipo `AbpValidationException`. O código da sua aplicação poderá lançar o `AbpValidationException`, mas na maioria das vezes não será necessário.
|
||||
|
||||
* A propriedade `ValidationErrors` do `AbpValidationException` contem a lista com os erros de validação.
|
||||
* O nível de log do `AbpValidationException` é definido como `Warning`. Todos os erros de validação são logados no [Sistema de Logging](Logging.md).
|
||||
* `AbpValidationException` é tratado automaticamente pelo ABP framework e é convertido em um erro utilizável com o código de status HTTP 400. Veja a documentação de [Manipulação de Exceção](Exception-Handling.md) para mais informações.
|
||||
|
||||
## Tópicos Avançados
|
||||
|
||||
### IObjectValidator
|
||||
|
||||
Além da validação automática, você pode querer validar um objeto manualmente. Nesse caso, [injete](Dependency-Injection.md) e use o serviço `IObjectValidator`:
|
||||
|
||||
* O método `ValidateAsync` valida o objeto informado baseado nas regras de validação e lança uma `AbpValidationException` se não estiver em um estado válido.
|
||||
|
||||
* `GetErrorsAsync` não lança uma exceção, somente retorna os erros de validação.
|
||||
|
||||
`IObjectValidator` é implementado pelo `ObjectValidator` por padrão. `ObjectValidator` é extensível; você pode implementar a interface `IObjectValidationContributor` para contribuir com uma lógica customizada. Exemplo:
|
||||
|
||||
````csharp
|
||||
public class MyObjectValidationContributor
|
||||
: IObjectValidationContributor, ITransientDependency
|
||||
{
|
||||
public Task AddErrorsAsync(ObjectValidationContext context)
|
||||
{
|
||||
//Get the validating object
|
||||
var obj = context.ValidatingObject;
|
||||
|
||||
//Add the validation errors if available
|
||||
context.Errors.Add(...);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
* Lembre-se de registrar sua classe no [DI](Dependency-Injection.md) (implementar `ITransientDependency` faz isso no exemplo anterior)
|
||||
* ABP vai automaticamente descobrir sua classe e utilizá-la em qualquer tipo de validação de objetos (incluindo chamadas de métodos de validação automáticas).
|
||||
|
||||
### IMethodInvocationValidator
|
||||
|
||||
`IMethodInvocationValidator` é utilizado para validar a chamada de um método. Ele utiliza internamente o `IObjectValidator` para validar os objetos passados na chamada do método. Você normalmente não precisa deste serviço, já que ele é utilizado automaticamente pelo framework, mas você pode querer reutilizar ou substituir na sua aplicação em alguns casos raros.
|
||||
|
||||
## Integração com FluentValidation
|
||||
|
||||
O pacote Volo.Abp.FluentValidation integra a biblioteca FluentValidation com o sistema de validação (implementando o `IObjectValidationContributor`). Veja o [documento de Integração com o FluentValidation](FluentValidation.md) para mais informações.
|
||||
|
||||
@ -0,0 +1,469 @@
|
||||
# ABP Dpar 集成
|
||||
|
||||
> 这个文档假设你已经熟悉[Dapr](https://dapr.io/)并且想在你的ABP应用中使用它.
|
||||
|
||||
[Dapr](https://dapr.io/) (分布式应用运行时)提供了简化微服务连接的API.它是一个开源项目,主要由微软支持.它也是CNCF(云原生计算基金会)项目,受到社区的信任.
|
||||
|
||||
ABP和Dapr有一些相似的特性,如服务到服务通信,分布式消息总线和分布式锁.然而,它们的目的完全不同.ABP的目标是通过提供自以为是的架构并提供必要的基础架构库,可重用模块和工具来正确实现该架构来提供端到端的开发人员体验.另一方面,Dapr的目的是提供一个运行时,将常见的微服务通信模式与应用程序逻辑解耦.
|
||||
|
||||
ABP和Dapr可以完美地在同一个应用程序中一起工作.ABP提供了一些包来提供更好的集成,其中Dapr功能与ABP相似.你可以根据[Dapr文档](https://docs.dapr.io/)使用其他Dapr功能,而不需要ABP集成包.
|
||||
|
||||
## ABP Dpar 集成包
|
||||
|
||||
ABP提供了以下NuGet包用于Dapr集成:
|
||||
|
||||
* [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr): 主要的Dapr集成包.所有其他包都依赖于此包.
|
||||
* [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr): 与Dapr的[服务调用](https://docs.dapr.io/developing-applications/building-blocks/service-invocation/service-invocation-overview/)集成的ABP的[动态](../API/Dynamic-CSharp-API-Clients.md)和[静态](../API/Static-CSharp-API-Clients.md)C# API客户端代理系统集成包.
|
||||
* [Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr): 使用Dapr的[发布和订阅](https://docs.dapr.io/developing-applications/building-blocks/pubsub/)构建块实现ABP的分布式事件总线.使用此包,你可以发送事件,但不能接收.
|
||||
* [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus): 提供从Dapr的[发布和订阅](https://docs.dapr.io/developing-applications/building-blocks/pubsub/)构建块接收事件的端点.使用此包发送和接收事件.
|
||||
* [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr): 使用Dapr的[分布式锁](https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/)构建块为ABP框架的[分布式锁定](../Distributed-Locking.md)服务.
|
||||
|
||||
在以下部分中,我们将看到如何使用这些包在ABP基础解决方案中使用Dapr.
|
||||
|
||||
## 基础
|
||||
|
||||
### 安装
|
||||
|
||||
> 这个部分解释了如何将[Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr)添加到你的项目中.如果你使用的是其他Dapr集成包,你可以跳过这个部分,因为这个包会被间接添加.
|
||||
|
||||
使用ABP CLI将[Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr) NuGet包添加到你的项目中:
|
||||
|
||||
* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI)如果你之前没有安装过.
|
||||
* 在你想要添加`Volo.Abp.Dapr`包的`.csproj`文件所在的目录中打开命令行(终端).
|
||||
* 运行`abp add-package Volo.Abp.Dapr`命令.
|
||||
|
||||
如果你想手动添加,安装 [Volo.Abp.Dapr](https://www.nuget.org/packages/Volo.Abp.Dapr) NuGet包到你的项目中,并在项目内的[ABP模块](../Module-Development-Basics.md)类中添加`[DependsOn(typeof(AbpDaprModule))]`.
|
||||
|
||||
### AbpDaprOptions
|
||||
|
||||
`AbpDaprOptions` 是配置全局Dapr设置的主要[选项类](../Options.md).**所有设置都是可选的,你大多数情况下不需要配置它们.** 如果你需要,你可以在[模块类](../Module-Development-Basics.md)的`ConfigureServices`方法中配置它:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
// ...
|
||||
});
|
||||
````
|
||||
|
||||
可用的`AbpDaprOptions`类属性:
|
||||
|
||||
* `HttpEndpoint` (可选):创建`DaprClient`对象时使用的HTTP端点.如果你没有指定,将使用默认值.
|
||||
* `GrpcEndpoint` (可选):创建`DaprClient`对象时使用的gRPC端点.如果你没有指定,将使用默认值.
|
||||
* `DaprApiToken` (可选):应用程序向Dapr发送请求时使用的[Dapr API token](https://docs.dapr.io/operations/security/api-token/).默认情况下,它从`DAPR_API_TOKEN`环境变量中填充(配置后由 Dapr 设置).有关详细信息,请参阅本文档的*安全*部分.
|
||||
* `AppApiToken` (可选):用于验证来自Dapr的请求的[应用程序API token](https://docs.dapr.io/operations/security/app-api-token/).默认情况下,它从`APP_API_TOKEN`环境变量中填充(配置后由 Dapr 设置).有关详细信息,请参阅本文档的*安全*部分.
|
||||
|
||||
或者, 你可以在 `appsettings.json` 文件的 `Dapr` 部分中配置选项.示例:
|
||||
|
||||
````csharp
|
||||
"Dapr": {
|
||||
"HttpEndpoint": "http://localhost:3500/"
|
||||
}
|
||||
````
|
||||
|
||||
### 注入DaprClient
|
||||
|
||||
ABP 将 `DaprClient` 类注册到 [依赖注入](../Dependency-Injection.md) 系统中.因此,你可以在需要时注入并使用它:
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly DaprClient _daprClient;
|
||||
|
||||
public MyService(DaprClient daprClient)
|
||||
{
|
||||
_daprClient = daprClient;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
// TODO: Use the injected _daprClient object
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
注入 `DaprClient` 是在应用程序代码中使用它的推荐方法.当你注入它时,将使用 `IAbpDaprClientFactory` 服务创建它,这会在下一节中将进行说明.
|
||||
|
||||
### IAbpDaprClientFactory
|
||||
|
||||
`IAbpDaprClientFactory` 可用于创建 `DaprClient` 或 `HttpClient` 对象来执行对 Dapr 的操作.它使用 `AbpDaprOptions`,因此你可以配置设置.
|
||||
|
||||
**示例用法:**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IAbpDaprClientFactory _daprClientFactory;
|
||||
|
||||
public MyService(IAbpDaprClientFactory daprClientFactory)
|
||||
{
|
||||
_daprClientFactory = daprClientFactory;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
// Create a DaprClient object with default options
|
||||
DaprClient daprClient = await _daprClientFactory.CreateAsync();
|
||||
|
||||
/* Create a DaprClient object with configuring
|
||||
* the DaprClientBuilder object */
|
||||
DaprClient daprClient2 = await _daprClientFactory
|
||||
.CreateAsync(builder =>
|
||||
{
|
||||
builder.UseDaprApiToken("...");
|
||||
});
|
||||
|
||||
// Create an HttpClient object
|
||||
HttpClient httpClient = await _daprClientFactory
|
||||
.CreateHttpClientAsync("target-app-id");
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`CreateHttpClientAsync` 方法还获取可选的 `daprEndpoint` 和 `daprApiToken` 参数.
|
||||
|
||||
> ABP使用`IAbpDaprClientFactory`创建Dapr客户端.你也可以在应用程序中使用Dapr API创建客户端对象.推荐使用`IAbpDaprClientFactory`,但不是必需的.
|
||||
|
||||
## C# API 客户端代理集成
|
||||
|
||||
ABP可以[动态](../API/Dynamic-CSharp-API-Clients.md)或[静态](../API/Static-CSharp-API-Clients.md)生成代理类,以便从Dotnet客户端应用程序调用HTTP API.在分布式系统中使用HTTP API是非常合理的.[Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr)包配置了客户端代理系统,因此它使用Dapr的服务调用构建块进行应用程序之间的通信.
|
||||
|
||||
### 安装
|
||||
|
||||
使用ABP CLI将[Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet包添加到项目(客户端):
|
||||
|
||||
* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI)如果你之前没有安装过.
|
||||
* 在你想要添加`Volo.Abp.Http.Client.Dapr`包的`.csproj`文件所在的目录中打开命令行(终端).
|
||||
* 运行`abp add-package Volo.Abp.Http.Client.Dapr`命令.
|
||||
|
||||
如果你想手动添加,安装 [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet包到你的项目中,并在项目内的[ABP模块](../Module-Development-Basics.md)类中添加`[DependsOn(typeof(AbpHttpClientDaprModule))]`.
|
||||
|
||||
### 配置
|
||||
|
||||
当你安装了[Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.Http.Client.Dapr) NuGet 包,所有你需要做的就是在`appsettings.json`或使用`AbpRemoteServiceOptions`[选项类](../Options.md)中配置ABP的远程服务选项.
|
||||
|
||||
**示例:**
|
||||
|
||||
````csharp
|
||||
{
|
||||
"RemoteServices": {
|
||||
"Default": {
|
||||
"BaseUrl": "http://dapr-httpapi/"
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`dapr-httpapi` 在这个例子中是你的Dapr配置中服务器应用程序的应用程序ID.
|
||||
|
||||
远程服务名称(示例中是`Default`)应该匹配动态客户端代理中`AddHttpClientProxies`调用或静态客户端代理中`AddStaticHttpClientProxies`调用中指定的远程服务名称.如果你的客户端只与一个服务器通信,使用`Default`是可以的.但是,如果你的客户端使用多个服务器,你通常在`RemoteServices`配置中有多个键. 你将远程服务端点配置为Dapr应用程序ID,在你使用ABP的客户端代理系统时它将自动工作并通过Dapr进行HTTP调用,
|
||||
|
||||
> 参阅[动态](../API/Dynamic-CSharp-API-Clients.md) 和 [static](../API/Static-CSharp-API-Clients.md)客户端代理文档,了解ABP的客户端代理系统的详细信息.
|
||||
|
||||
## 分布式事件总线集成
|
||||
|
||||
[ABP的分布式事件总线](../Distributed-Event-Bus.md)系统提供了一个方便的抽象,允许应用程序通过事件异步通信.ABP提供了各种分布式消息系统(如RabbitMQ,Kafka和Azure)的集成包.Dapr也有一个[发布和订阅构建块](https://docs.dapr.io/developing-applications/building-blocks/pubsub/pubsub-overview/),用于相同的目的:分布式消息/事件.
|
||||
|
||||
ABP的[Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr)和[Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus)包可以使用Dapr基础设施来实现ABP的分布式事件总线.
|
||||
|
||||
任何类型的应用程序(例如,控制台或ASP.NET Core应用程序)都可以使用[Volo.Abp.EventBus.Dapr]包通过Dapr发布事件.为了能够接收消息(通过订阅事件),你需要安装[Volo.Abp.AspNetCore.Mvc.Dapr.EventBus]包,并且你的应用程序应该是ASP.NET Core应用程序.
|
||||
|
||||
### 安装
|
||||
|
||||
如果你的应用程序是ASP.NET Core应用程序并且你想发送和接收事件,你需要按照下面的描述安装[Volo.Abp.AspNetCore.Mvc.Dapr.EventBus]包:
|
||||
|
||||
* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI)如果你之前没有安装过.
|
||||
* 在你想要添加`Volo.Abp.AspNetCore.Mvc.Dapr.EventBus`包的`.csproj`文件所在的目录中打开命令行(终端).
|
||||
* 运行`abp add-package Volo.Abp.AspNetCore.Mvc.Dapr.EventBus`命令.
|
||||
|
||||
如果你想手动添加,安装 [Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) NuGet包到你的项目中,并在项目内的[ABP模块](../Module-Development-Basics.md)类中添加`[DependsOn(typeof(AbpAspNetCoreMvcDaprEventBusModule))]`.
|
||||
|
||||
> **如果你安装了[Volo.Abp.AspNetCore.Mvc.Dapr.EventBus](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus)包, 那么你不需要安装[Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr)包,因为它已经由第一个包引用**
|
||||
|
||||
如果你的应用程序不是ASP.NET Core应用程序,你不能从Dapr接收事件,至少使用ABP的集成包(如果你想在不同类型的应用程序中接收事件,请参阅[Dapr的文档](https://docs.dapr.io/developing-applications/building-blocks/pubsub/howto-publish-subscribe/)).但是你仍然可以使用[Volo.Abp.EventBus.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr)包发布消息.在这种情况下,请按照下面的步骤将该包安装到你的项目中:
|
||||
|
||||
* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI)如果你之前没有安装过.
|
||||
* 在你想要添加`Volo.Abp.EventBus.Dapr`包的`.csproj`文件所在的目录中打开命令行(终端).
|
||||
* 运行`abp add-package Volo.Abp.EventBus.Daprs`命令.
|
||||
|
||||
如果你想手动添加,安装 [Volo.Abp.Http.Client.Dapr](https://www.nuget.org/packages/Volo.Abp.EventBus.Dapr) NuGet包到你的项目中,并在项目内的[ABP模块](../Module-Development-Basics.md)类中添加`[DependsOn(typeof(AbpEventBusDaprModule))]`.
|
||||
|
||||
### 配置
|
||||
|
||||
你可以为Dapr配置`AbpDaprEventBusOptions`[选项类](../Options.md):
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprEventBusOptions>(options =>
|
||||
{
|
||||
options.PubSubName = "pubsub";
|
||||
});
|
||||
````
|
||||
|
||||
可用的`AbpDaprEventBusOptions`类的属性:
|
||||
|
||||
* `PubSubName` (可选): 通过`DaprClient.PublishEventAsync`方法发布消息时的`pubsubName`参数.默认值:`pubsub`.
|
||||
|
||||
### ABP订阅端点
|
||||
|
||||
ABP提供了以下端点来接收来自Dapr的事件:
|
||||
|
||||
* `dapr/subscribe`: Dapr使用此端点从应用程序获取订阅列表.ABP会自动返回所有分布式事件处理程序类和具有`Topic`属性的自定义控制器操作的订阅.
|
||||
* `api/abp/dapr/event`: 用于接收来自Dapr的所有事件的统一端点.ABP根据主题名称将事件分派给您的事件处理程序.
|
||||
|
||||
> **由于ABP提供了标准的`dapr/subscribe`端点,所以你不应该手动调用Dapr的`app.MapSubscribeHandler()`方法.** 如果你想支持[CloudEvents](https://cloudevents.io/)标准,你可以在你的ASP.NET Core管道中使用`app.UseCloudEvents()`中间件.
|
||||
|
||||
### 用法
|
||||
|
||||
#### ABP的方式
|
||||
|
||||
你可以按照[ABP的分布式事件总线文档](../Distributed-Event-Bus.md)来学习如何以ABP的方式发布和订阅事件.你的应用程序代码不需要做任何改变就可以使用Dapr的发布-订阅功能.ABP将自动为你的事件处理程序类(实现`IDistributedEventHandler`接口)订阅Dapr.
|
||||
|
||||
ABP提供了 `api/abp/dapr/event`
|
||||
|
||||
**示例:使用`IDistributedEventBus`服务发布事件**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IDistributedEventBus _distributedEventBus;
|
||||
|
||||
public MyService(IDistributedEventBus distributedEventBus)
|
||||
{
|
||||
_distributedEventBus = distributedEventBus;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
await _distributedEventBus.PublishAsync(new StockCountChangedEto
|
||||
{
|
||||
ProductCode = "AT837234",
|
||||
NewStockCount = 42
|
||||
});
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
**示例:通过实现`IDistributedEventHandler`接口来订阅事件**
|
||||
|
||||
````csharp
|
||||
public class MyHandler :
|
||||
IDistributedEventHandler<StockCountChangedEto>,
|
||||
ITransientDependency
|
||||
{
|
||||
public async Task HandleEventAsync(StockCountChangedEto eventData)
|
||||
{
|
||||
var productCode = eventData.ProductCode;
|
||||
// ...
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
参阅[ABP的分布式事件总线文档](../Distributed-Event-Bus.md)来了解细节.
|
||||
|
||||
#### 使用Dapr API
|
||||
|
||||
在ABP的标准分布式事件总线系统之外,你还可以使用Dapr的API来发布事件.
|
||||
|
||||
> 如果你直接使用Dapr API来发布事件,你可能无法从ABP的标准分布式事件总线功能中受益,比如outbox/inbox模式的实现.
|
||||
|
||||
**示例:使用`DaprClient`发布事件**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly DaprClient _daprClient;
|
||||
|
||||
public MyService(DaprClient daprClient)
|
||||
{
|
||||
_daprClient = daprClient;
|
||||
}
|
||||
|
||||
public async Task DoItAsync()
|
||||
{
|
||||
await _daprClient.PublishEventAsync(
|
||||
"pubsub", // pubsub name
|
||||
"StockChanged", // topic name
|
||||
new StockCountChangedEto // event data
|
||||
{
|
||||
ProductCode = "AT837234",
|
||||
NewStockCount = 42
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
**示例:通过创建ASP.NET Core控制器来订阅事件**
|
||||
|
||||
````csharp
|
||||
public class MyController : AbpController
|
||||
{
|
||||
[HttpPost("/stock-changed")]
|
||||
[Topic("pubsub", "StockChanged")]
|
||||
public async Task<IActionResult> TestRouteAsync(
|
||||
[FromBody] StockCountChangedEto model)
|
||||
{
|
||||
HttpContext.ValidateDaprAppApiToken();
|
||||
|
||||
// Do something with the event
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`HttpContext.ValidateDaprAppApiToken()` 扩展方法由ABP提供,用于检查请求是否来自Dapr.这是可选的.如果你想启用验证,你应该配置Dapr将App API令牌发送到你的应用程序.如果没有配置,`ValidateDaprAppApiToken()`不会执行任何操作.参阅[Dapr的App API令牌文档](https://docs.dapr.io/operations/security/app-api-token/)了解更多信息.还可以参阅本文档中的**AbpDaprOptions**和**安全**部分.
|
||||
|
||||
参阅[Dapr的文档](https://docs.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/publish-subscribe)来了解使用Dapr API发送和接收事件的细节.
|
||||
|
||||
## 分布式锁
|
||||
|
||||
> Dapr的分布式锁功能目前处于Alpha阶段,可能还不稳定.在这一点上,不建议用Dapr来替换ABP的分布式锁.
|
||||
|
||||
ABP提供了一个[分布式锁](../Distributed-Locking.md)抽象来控制多个应用程序对共享资源的访问.Dapr也有一个[分布式锁构建块](https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/).[Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr)包使ABP使用Dapr的分布式锁系统.
|
||||
|
||||
### 安装
|
||||
|
||||
使用ABP CLI将[Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.DistributedLocking.Dapr)NuGet包添加到项目(客户端):
|
||||
|
||||
* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI)如果你之前没有安装过.
|
||||
* 在你想要添加`Volo.Abp.DistributedLocking.Dapr`包的`.csproj`文件所在的目录中打开命令行(终端).
|
||||
* 运行`abp add-package Volo.Abp.DistributedLocking.Dapr`命令.
|
||||
|
||||
如果你想手动添加,安装 [Volo.Abp.DistributedLocking.Dapr](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.Dapr.EventBus) NuGet包到你的项目中,并在项目内的[ABP模块](../Module-Development-Basics.md)类中添加`[DependsOn(typeof(AbpDistributedLockingDaprModule))]`.
|
||||
|
||||
### 配置
|
||||
|
||||
你可以在[你的模块](../Module-Development-Basics.md)的`ConfigureServices`方法中使用`AbpDistributedLockDaprOptions`选项类来配置Dapr分布式锁:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDistributedLockDaprOptions>(options =>
|
||||
{
|
||||
options.StoreName = "mystore";
|
||||
});
|
||||
````
|
||||
|
||||
以下选项可用:
|
||||
|
||||
* **`StoreName`** (必需):Dapr使用的存储库名称.锁键名称在同一存储库中范围内.这意味着不同的应用程序可以在不同的存储库中获取相同的锁名称.对于要控制访问的相同资源,请使用相同的存储库名称.
|
||||
* `Owner` (可选):`DaprClient.Lock`方法使用的`owner`值.如果你不指定,ABP使用一个随机值,这在一般情况下是可以的.
|
||||
* `DefaultExpirationTimeout` (可选):锁过期后的默认值.默认值:2分钟.
|
||||
|
||||
### 用法
|
||||
|
||||
你可以注入并使用`IAbpDistributedLock`服务,就像在[分布式锁文档](../Distributed-Locking.md)中解释的那样.
|
||||
|
||||
**示例:**
|
||||
|
||||
````csharp
|
||||
public class MyService : ITransientDependency
|
||||
{
|
||||
private readonly IAbpDistributedLock _distributedLock;
|
||||
|
||||
public MyService(IAbpDistributedLock distributedLock)
|
||||
{
|
||||
_distributedLock = distributedLock;
|
||||
}
|
||||
|
||||
public async Task MyMethodAsync()
|
||||
{
|
||||
await using (var handle =
|
||||
await _distributedLock.TryAcquireAsync("MyLockName"))
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
// your code that access the shared resource
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
这里有两点关于`TryAcquireAsync`方法我们应该提到,与ABP的标准用法不同:
|
||||
|
||||
* `timeout` 参数目前没有使用(即使你指定了它),因为Dapr不支持等待获取锁.
|
||||
* Dapr 使用过期超时系统(这意味着即使你不通过释放处理程序来释放锁,锁也会在超时后自动释放).但是,ABP的`TryAcquireAsync`方法没有这样的参数.目前,你可以在应用程序中将`AbpDistributedLockDaprOptions.DefaultExpirationTimeout`设置为全局值.
|
||||
|
||||
Dapr的分布式锁功能目前处于Alpha阶段,其API是可能会改变的候选者.如果你想要使用它,你可以这样做,但是要准备好未来的变化.目前,我们建议使用ABP的[分布式锁文档](../Distributed-Locking.md)中提到的[DistributedLock](https://github.com/madelson/DistributedLock)库.
|
||||
|
||||
## 安全
|
||||
|
||||
如果你使用Dapr,你的应用程序中的大部分或全部传入和传出请求都会通过Dapr.Dapr使用两种API令牌来保护应用程序与Dapr之间的通信.
|
||||
|
||||
### Dapr API Token
|
||||
|
||||
> 这个令牌默认情况下是自动设置的,通常你不需要关心它.
|
||||
|
||||
[在Dapr中启用API令牌身份验证](https://docs.dapr.io/operations/security/api-token/)文档描述了Dapr API令牌是什么以及如何配置.如果你想为你的应用程序启用它,请阅读该文档.
|
||||
|
||||
如果你启用了Dapr API令牌,你应该在你的应用程序中向Dapr发送该令牌.`AbpDaprOptions`定义了一个`DaprApiToken`属性,作为在你的应用程序中配置Dapr API令牌的中心点.
|
||||
|
||||
`DaprApiToken`属性的默认值是从`DAPR_API_TOKEN`环境变量设置的,并且该环境变量是在Dapr运行时设置的.所以,大多数情况下,你不需要在你的应用程序中配置`AbpDaprOptions.DaprApiToken`.但是,如果你需要配置(或覆盖它),你可以在模块类的`ConfigureServices`方法中这样做,如下面的代码块所示:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
options.DaprApiToken = "...";
|
||||
});
|
||||
````
|
||||
|
||||
或者你可以在`appsettings.json`文件中设置它:
|
||||
|
||||
````json
|
||||
"Dapr": {
|
||||
"DaprApiToken": "..."
|
||||
}
|
||||
````
|
||||
|
||||
一旦你设置了它,它就会在你注入`DaprClient`或使用`IAbpDaprClientFactory`时使用.如果你需要在应用程序中使用该值,你可以注入`IDaprApiTokenProvider`并使用其`GetDaprApiToken()`方法.
|
||||
|
||||
### App API Token
|
||||
|
||||
> 启用App API令牌验证是强烈推荐的.否则,例如,任何客户端都可以直接调用你的事件订阅端点,你的应用程序就像发生了事件一样(如果你的事件订阅端点中没有其他安全策略).
|
||||
|
||||
[在Dapr中使用令牌身份验证请求身份验证](https://docs.dapr.io/operations/security/app-api-token/)文档描述了App API令牌是什么以及如何配置.如果你想为你的应用程序启用它,请阅读该文档.
|
||||
|
||||
如果你启用了App API令牌,你可以验证它以确保请求来自Dapr.ABP提供了有用的快捷方式来验证它.
|
||||
|
||||
**示例:在事件处理HTTP API中验证App API令牌**
|
||||
|
||||
````csharp
|
||||
public class MyController : AbpController
|
||||
{
|
||||
[HttpPost("/stock-changed")]
|
||||
[Topic("pubsub", "StockChanged")]
|
||||
public async Task<IActionResult> TestRouteAsync(
|
||||
[FromBody] StockCountChangedEto model)
|
||||
{
|
||||
// Validate the App API token!
|
||||
HttpContext.ValidateDaprAppApiToken();
|
||||
|
||||
// Do something with the event
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
````
|
||||
|
||||
`HttpContext.ValidateDaprAppApiToken()` 是ABP框架提供的扩展方法.如果HTTP头中缺少或错误的令牌,则会抛出`AbpAuthorizationException`(头名称为`dapr-api-token`).你也可以注入`IDaprAppApiTokenValidator`并使用其方法在任何服务中验证令牌(不仅仅是在控制器类中).
|
||||
|
||||
你可以配置`AbpDaprOptions.AppApiToken`,如果你想设置(或覆盖)App API令牌值.默认值由`APP_API_TOKEN`环境变量设置.你可以在模块类的`ConfigureServices`方法中这样做,如下面的代码块所示:
|
||||
|
||||
````csharp
|
||||
Configure<AbpDaprOptions>(options =>
|
||||
{
|
||||
options.AppApiToken = "...";
|
||||
});
|
||||
````
|
||||
|
||||
或者你可以在`appsettings.json`文件中设置它:
|
||||
|
||||
````json
|
||||
"Dapr": {
|
||||
"AppApiToken": "..."
|
||||
}
|
||||
````
|
||||
|
||||
如果你需要在应用程序中使用该值,你可以注入`IDaprApiTokenProvider`并使用其`GetAppApiToken()`方法.
|
||||
|
||||
## 另请参阅
|
||||
|
||||
* [Dapr for .NET Developers](https://docs.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/)
|
||||
* [Dapr官方文档](https://docs.dapr.io/)
|
||||
@ -0,0 +1,7 @@
|
||||
@if (LayoutHookViewModel.Hooks.Any())
|
||||
{
|
||||
foreach (var hook in LayoutHookViewModel.Hooks)
|
||||
{
|
||||
<DynamicComponent Type="@hook.ComponentType" />
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
// This file is automatically generated by ABP framework to use MVC Controllers from CSharp
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Volo.Abp.Http.Client;
|
||||
using Volo.Abp.Http.Modeling;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Volo.Abp.Http.Client.ClientProxying;
|
||||
using Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations;
|
||||
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations.ClientProxies;
|
||||
|
||||
[Dependency(ReplaceServices = true)]
|
||||
[ExposeServices(typeof(IAbpApplicationLocalizationAppService), typeof(AbpApplicationLocalizationClientProxy))]
|
||||
public partial class AbpApplicationLocalizationClientProxy : ClientProxyBase<IAbpApplicationLocalizationAppService>, IAbpApplicationLocalizationAppService
|
||||
{
|
||||
public virtual async Task<ApplicationLocalizationDto> GetAsync(ApplicationLocalizationRequestDto input)
|
||||
{
|
||||
return await RequestAsync<ApplicationLocalizationDto>(nameof(GetAsync), new ClientProxyRequestTypeValue
|
||||
{
|
||||
{ typeof(ApplicationLocalizationRequestDto), input }
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
// This file is part of AbpApplicationLocalizationClientProxy, you can customize it here
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations.ClientProxies;
|
||||
|
||||
public partial class AbpApplicationLocalizationClientProxy
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations;
|
||||
|
||||
public class ApplicationConfigurationRequestOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Set to true to fill the Values property in <see cref="ApplicationConfigurationDto.Localization"/>.
|
||||
/// </summary>
|
||||
public bool IncludeLocalizationResources { get; set; } = true;
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations;
|
||||
|
||||
[Serializable]
|
||||
public class ApplicationLocalizationDto
|
||||
{
|
||||
public Dictionary<string, ApplicationLocalizationResourceDto> Resources { get; set; }
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations;
|
||||
|
||||
public class ApplicationLocalizationRequestDto
|
||||
{
|
||||
[Required]
|
||||
public string CultureName { get; set; }
|
||||
|
||||
public bool OnlyDynamics { get; set; }
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations;
|
||||
|
||||
[Serializable]
|
||||
public class ApplicationLocalizationResourceDto
|
||||
{
|
||||
public Dictionary<string, string> Texts { get; set; }
|
||||
|
||||
public string[] BaseResources { get; set; }
|
||||
}
|
||||