Hello Volosoft,
I am getting the weird issue inside Angular project and ASP.NET Core 2.0 project (ASPNETZero version 5.0).
Inside the ASPNETZero Core project, I have used "AbpAuthorize(Permission)" for authorizing user. Ideally, if user doesn't have permission, they cannot access the resource. However, the weird thing is: I see the popup Not having permission, but after that, I still get the data. Here is my code:
Angular Code:
resetForm(model) {
this.isBusy = true;
setTimeout(() => {
this.form.resetForm(model);
});
const { tenantId, languageCode } = this.getSectionInfo();
this._unitsService.getMember(tenantId, model.memberId, languageCode)
.subscribe(res => {
setTimeout(() => {
this.form.resetForm(res);
this.DOB = res.dateOfBirth.toDate();
this.isBusy = false;
});
});
}
Services proxy code:
getMember(tenantId: number, memberId: number, language: string): Observable<MemberReadOutput> {
let url_ = this.baseUrl + "/api/services/app/Units/GetMember?";
if (tenantId === undefined || tenantId === null)
throw new Error("The parameter 'tenantId' must be defined and cannot be null.");
else
url_ += "tenantId=" + encodeURIComponent("" + tenantId) + "&";
if (memberId === undefined || memberId === null)
throw new Error("The parameter 'memberId' must be defined and cannot be null.");
else
url_ += "memberId=" + encodeURIComponent("" + memberId) + "&";
if (language !== undefined)
url_ += "language=" + encodeURIComponent("" + language) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
method: "get",
headers: new Headers({
"Content-Type": "application/json",
"Accept": "application/json"
})
};
return this.http.request(url_, options_).flatMap((response_ : any) => {
return this.processGetMember(response_);
}).catch((response_: any) => {
if (response_ instanceof Response) {
try {
return this.processGetMember(<any>response_);
} catch (e) {
return <Observable<MemberReadOutput>><any>Observable.throw(e);
}
} else
return <Observable<MemberReadOutput>><any>Observable.throw(response_);
});
}
protected processGetMember(response: Response): Observable<MemberReadOutput> {
const status = response.status;
let _headers: any = response.headers ? response.headers.toJSON() : {};
if (status === 200) {
const _responseText = response.text();
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 ? MemberReadOutput.fromJS(resultData200) : new MemberReadOutput();
return Observable.of(result200);
} else if (status !== 200 && status !== 204) {
const _responseText = response.text();
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}
return Observable.of<MemberReadOutput>(<any>null);
}
C# Code in Core project:
[AbpAuthorize(AppPermissions.Staffs_Units_Member_ReadAll)]
public async Task<MemberReadOutput> GetMember(int tenantId, int memberId, string language = null)
{
try
{
_httpClient = new UnitsHttpClient(_baseUrl, GetHttpClient());
var _response = await _httpClient.ApiByTenantIdMemberByMemberIdGetAsync(tenantId, memberId, language);
var user = await UserManager.GetUserByIdAsync(memberId);
if (user.ProfilePictureId.HasValue)
{
var profile = await _profileService.GetProfilePictureById(user.ProfilePictureId.Value);
_response.ProfilePicture = "data:image/jpeg;base64," + profile.ProfilePicture;
}
_response.Name = user.Name;
_response.Surname = user.Surname;
_response.PhoneNumber = user.PhoneNumber;
return _response;
}
catch (SwaggerException e)
{
throw new UserFriendlyException(int.Parse(e.StatusCode), e.Message);
}
}
I have made a demo, but it contains some confidential information. Therefore I will send you via email ASAP.
Please review it, thanks.
Hello,
I am developing the download file module which provides a way to get authorized file by Encrypted Token (using ASPNETZero Encrypted Token) with its information.
Currently, I am stuck at getting data from the right tenant database from the encrypted token (After decrypted the token to get the real token, how can I initialize IRepository for the right tenant database?)
private readonly IAppFolders _appFolders;
private readonly IRepository < OnePlaceFile, Guid > _fileRepository;
public FileController(IAppFolders appFolders, IRepository < OnePlaceFile, Guid > fileRepository) {
_appFolders = appFolders;
_fileRepository = fileRepository;
}
[DisableAuditing]
[AllowAnonymous]
public async Task < ActionResult > OnePlaceDownloadFileWithToken(Guid fileId, string encToken) {
if (!ValidateToken(encToken)) throw new UserFriendlyException(L("RequestedFileDoesNotExists"));
var file = await _fileRepository.FirstOrDefaultAsync(fileId);
if (file == null) throw new UserFriendlyException(L("RequestedFileDoesNotExists"));
var filePath = Path.Combine(_appFolders.TempFileDownloadFolder,
file.TenantId.ToString(),
file.ModuleName,
file.ReferenceId,
file.Id.ToString());
if (!System.IO.File.Exists(filePath)) {
throw new UserFriendlyException(L("RequestedFileDoesNotExists"));
}
var fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, file.MimeType, file.FileName);
}
private bool ValidateToken(string encToken) {
try {
var token = SimpleStringCipher.Instance.Decrypt(encToken, AppConsts.DefaultPassPhrase);
return true;
} catch (Exception e) {
return false;
}
}
Hello Volosoft team,
After I made some API, I want to generate the proxies for Angular. I used refresh.bat in nswag folder and open file service.config.nswag to change the URL (only change that line and saved).
When I run the refresh.bat, the generator runs well. But when I opened the file, I see many lines have similar to this: "ListResultDto`1OfOfFlatPermissionWithLevelDtoAndSharedAnd_0AndCulture=neutralAndPublicKeyToken=null" and this make error in NPM Start.
Included in this topic are
Please help me, because my deadline is very soon from now. Thanks
Hi, I always get the problem of validation in ASPNET Zero. Here are my things. To describe more the issue, I want to use ASPNETZero as the API Gateway. And with the same request data, I can POST successfully to the private API. Therefore, I don't know what is just happen with ASPNETZero Validation (the request just failed in the validation phase, and the program doesn't jump into the breakpoint inside LibraryAppService).
ILibraryAppService.cs
public interface ILibraryAppService : IApplicationService
{
Task ApiCategoryPostAsync(string tenantId, CategoryInput entityInput = null, CancellationToken cancellationToken = default(CancellationToken));
}
LibraryAppService.cs
public async Task ApiCategoryPostAsync(string tenantId, CategoryInput entityInput,
CancellationToken cancellationToken = default(CancellationToken))
{
_libraryClient = new LibraryHttpClient(_baseUrl, this.GetHttpClient());
await _libraryClient.ApiCategoryPostAsync(tenantId, entityInput, cancellationToken);
}
CategoryInput.cs
public class CategoryInput
{
[Required]
public TranslationInput CategoryName { get; set; }
public TranslationInput CategoryDescription { get; set; }
public string ParentId { get; set; }
[Required]
public ChosenBuildingInput[] BuildingStatusList { get; set; }
}
public class ChosenBuildingInput
{
public string BuildingId { get; set; }
public bool IsActive { get; set; }
}
TranslationInput.cs
public class TranslationInput
{
public string ENG { get; set; }
public string VIE { get; set; }
public string KHM { get; set; }
public string THA { get; set; }
public string LAO { get; set; }
public string CHI { get; set; }
public string KOR { get; set; }
public string JPN { get; set; }
}
Request Data (From Swagger)
curl -X POST --header 'Content-Type: application/json-patch+json' --header 'Accept: application/json' -d '{ \
"categoryName": { \
"eng": "Manga", \
"vie": "Manga Nhật Bản" \
}, \
"categoryDescription": { \
"eng": "Documents that is relevant to Manga", \
"vie": "Tài liệu liên quan đến truyện Manga" \
}, \
"buildingStatusList": [ \
{ \
"buildingId": "T1", \
"isActive": true \
}, \
{ \
"buildingId": "T2", \
"isActive": true \
} \
] \
}' 'http://localhost:5000/api/services/app/Library/ApiCategoryPostAsync?tenantId=3'
ResponseData:
{
"result": null,
"targetUrl": null,
"success": false,
"error": {
"code": 0,
"message": "Your request is not valid!",
"details": "The following errors were detected during validation.\r\n - \r\n",
"validationErrors": [
{
"message": "",
"members": [
""
]
}
]
},
"unAuthorizedRequest": false,
"__abp": true
}
Log File
WARN 2017-12-01 23:50:29,266 [9 ] Mvc.ExceptionHandling.AbpExceptionFilter - Method arguments are not valid! See ValidationErrors for details.
Abp.Runtime.Validation.AbpValidationException: Method arguments are not valid! See ValidationErrors for details.
at Abp.Runtime.Validation.Interception.MethodInvocationValidator.ThrowValidationError() in D:\Github\aspnetboilerplate\src\Abp\Runtime\Validation\Interception\MethodInvocationValidator.cs:line 128
at Abp.Runtime.Validation.Interception.MethodInvocationValidator.Validate() in D:\Github\aspnetboilerplate\src\Abp\Runtime\Validation\Interception\MethodInvocationValidator.cs:line 94
at Abp.AspNetCore.Mvc.Validation.AbpValidationActionFilter.<OnActionExecutionAsync>d__3.MoveNext() in D:\Github\aspnetboilerplate\src\Abp.AspNetCore\AspNetCore\Mvc\Validation\AbpValidationActionFilter.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextExceptionFilterAsync>d__23.MoveNext()
WARN 2017-12-01 23:50:29,275 [9 ] Mvc.ExceptionHandling.AbpExceptionFilter - There are 1 validation errors:
WARN 2017-12-01 23:50:29,275 [9 ] Mvc.ExceptionHandling.AbpExceptionFilter - ()
INFO 2017-12-01 23:50:30,821 [9 ] etCore.Mvc.Internal.ObjectResultExecutor - Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
INFO 2017-12-01 23:50:30,851 [9 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action OnePlace.O1.OnePlace.Library.LibraryAppService.ApiCategoryPostAsync (OnePlace.O1.Application) in 5833.2027ms
INFO 2017-12-01 23:50:30,860 [9 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 6335.7659ms 400 application/json; charset=utf-8
Hello, If it is OK, in the next version, I hope you guys - ASPNETZero team should consider to add the authorize button by default for users to test the API easier.
Something just easy like this:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "O1 API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
options.IncludeXmlComments(Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "xml"));
**options.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
In = "header",
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = "apiKey"
});
});**
Hello, I want to ask a few questions about service in Application project.
1/ I am creating a service (let call it LibraryAppService) and in that service, I want to get the token from current request (or the UserId, TenantId to call other API - which can use the token that AspNetZero issued). How can I do that?
2/ I don't want to hardcode my other API URL inside the LibraryAppService but I want to put it inside AppSettings.json. How can I do that?
Thank you very much.
Hello, Does the Angular project support Server-rendering from ASPNET Core or NodeJS? I need this to increase the speed of loading the login page. Thanks.
hi, we are working on project which need features of new metronic theme v5.x with angular 4, no sure when it live?
Hello,
I am trying to config two things which are relevant to IConfigurationRoot to get config inside AppSettings.json.
I want to inject IConfiguration to file AngularAppUrlService.cs. However, those fields are read-only therefore I cannot assign new value to it.
I implement new class for Email Sender Service and I put it outside ASPNETZero Sourcecode. However, I cannot inject IConfigurationRoot to my class. I got this error.
Please help me to archive this. Thank you