Base solution for your next web application

Activities of "khai"

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 ismcagdas,

I did all those things well with your reference now. My question about "And do you provide a method to verify the token in this case?" is also in your reference (context.Token = SimpleStringCipher.Instance.Decrypt(encToken, AppConsts.DefaultPassPhrase);)

Thank you.

So in case that I just have the encrypted Token without any session in the browser, can I initialize IRepository<> for the right tenant? I need this because those files could be read from outside the ABP Application (using Google Docs Online reader, Office Web App)

And do you provide a method to verify the token in this case?

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;
 }
}

I figured out what just happened to my code. I added the: options.CustomSchemaIds(x => x.FullName); to fix the other problems according to <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2663">https://github.com/aspnetboilerplate/as ... ssues/2663</a>.

My current solution is to change the class name of my viewmodel. But is there any other solution?

Here is my Swagger.json file: <a class="postlink" href="https://gist.github.com/LAITRUNGMINHDUC/ad79f64e852049a11dbde274e5574b63">https://gist.github.com/LAITRUNGMINHDUC ... 74e5574b63</a>. This is the first time I generate the proxy file, and I just change the port of localhost to localhost:5000.

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

Hello aaron, Thanks for your great support. I did it. I don't think that cancelationToken made it wrong.

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

Hi, I tried and nothing happen...

<cite>ismcagdas: </cite> Hi,

Can you try to define your App service like this:

public partial class LibraryAppService : OnePlaceAppServiceBase, ILibraryAppService
Showing 1 to 10 of 27 entries