Open Closed

API not working when called from an application ,but was working fine with postman. #6473


User avatar
0
Anjaneyulu created
  • ABP Framework version: v7.3.2
  • UI Type: MVC
  • Database System: EF Core (SQL Server
  • Tiered (for MVC) or Auth Server Separated (for Angular): yes/
  • Exception message and full stack trace:
Task was cancelled & 
t Microsoft.EntityFrameworkCore.Storage.RelationalCommand.<ExecuteReaderAsync>d__19.MoveNext() at
 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.<ExecuteReaderAsync>d__19.MoveNext() at 
 Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.<<PopulateSplitIncludeCollectionAsync>g__InitializeReaderAsync|27_0>d`2.MoveNext() at
  Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.&lt;ExecuteAsync&gt;d__7`2.MoveNext() at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.<PopulateSplitIncludeCollectionAsync>d__27`2.MoveNext() at 
  Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.&lt;TaskAwaiter&gt;d__37.MoveNext() at 
  Microsoft.EntityFrameworkCore.Query.Internal.SplitQueryingEnumerable`1.AsyncEnumerator.<MoveNextAsync>d__21.MoveNext() at 
  Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.<SingleOrDefaultAsync>d__15`1.MoveNext() at 
  Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.&lt;SingleOrDefaultAsync&gt;d__15`1.MoveNext() at 
  Volo.Abp.Domain.Repositories.EntityFrameworkCore.EfCoreRepository`3.&lt;FindAsync&gt;d__2.MoveNext() at 
  Castle.DynamicProxy.AsyncInterceptorBase.&lt;ProceedAsynchronous&gt;d__14`1.MoveNext() at 
  Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.&lt;ProceedAsync&gt;d__7.MoveNext() at Volo.Abp.Uow.UnitOfWorkInterceptor.&lt;InterceptAsync&gt;d__2.MoveNext() at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.<InterceptAsync>d__3`1.MoveNext() at XSense.Controllers.ComputerController.&lt;GetUserInfo&gt;d__58.MoveNext() in
  • Steps to reproduce the issue:

In the GetUserInfo api > I see an exception at >>>>> var userinfo = await identityrepository.FindAsync("userid");

Im getting the above exception when i call this api from APP, but it works fine with postman. I have checked the parameters and all are same.

Can you please let me know the possible cause.


5 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Im getting the above exception when i call this api from APP,

    Can you share the call code ?

  • User Avatar
    0
    Anjaneyulu created

    Hi,

    Calling in golang application:

    API : APIGetUser             string = "/api/pc/get-user-info"
    

    Libhandle is structure to handle the api & db configuration , Where is client is an http client implementationf for api calls.

    type LibHandle struct {
    	db  *adapter.Adapter
    	log logger.Logger
    	cfg *Config
    	c   *Client
    }
    

    Calling Function :

    func (h *LibHandle) getUser(userName string, localUser bool) (*UserCrdential, bool, error) {
    	uc, noLocalUser := h.getLocalUser(userName)
    	mr := make(map[string]interface{})
    	mr["UID"] = h.getUID()
    	mr["UserName"] = userName
    
    	``` req, err := h.getRequest("POST", APIGetUser, mr) ```
    	if err != nil {
    		h.log.Error("Failed to get user, failed to create API request", "err", err)
    		if noLocalUser {
    			return nil, false, err
    		}
    		return uc, true, nil
    	}
    	// q := req.URL.Query()
    	// q.Add("UID", h.getUID())
    	// q.Add("UserName", userName)
    	// req.URL.RawQuery = q.Encode()
    
    	```resp, err := h.c.Do(req) ```
    	
    	if err != nil {
    		h.log.Error("Failed to get user, invalid response from the server", "err", err)
    		if noLocalUser {
    			return nil, false, err
    		}
    		return uc, true, nil
    	}
    	defer resp.Body.Close()
    	if resp.StatusCode != http.StatusOK {
    		h.log.Error("Failed to get user, get user failed with status", "status", resp.StatusCode)
    		if noLocalUser {
    			return nil, false, err
    		}
    		return uc, true, nil
    	}
    	var ud UserDetials
    	err = jsonutil.DecodeJSONFromReader(resp.Body, &ud)
    	if err != nil {
    		h.log.Error("Failed to get user, failed to parse the json", "err", err)
    		if noLocalUser {
    			return nil, false, err
    		}
    		return uc, true, nil
    	}
    
    }
    

    Function : Common function to form a request based on the provided method,route and inputs >> h.getRequest("POST", APIGetUser, Mr)

    
    func (h *LibHandle) getRequest(method string, path string, model interface{}) (*http.Request, error) {
    	req, err := h.c.JSONRequest(method, path, model)
    	if err != nil {
    		return nil, err
    	}
    	//req.Header.Add("XSENSE-APP-ID", h.cfg.AppID)
    	req.Header.Add("XSENSE-API-KEY", h.cfg.AppSecret)
    	return req, nil
    }
    
    func (c *Client) JSONRequest(method string, requestPath string, model interface{}) (*http.Request, error) {
    	var body *bytes.Buffer
    	if model != nil {
    		j, err := json.Marshal(model)
    		if err != nil {
    			return nil, err
    		}
    		body = bytes.NewBuffer(j)
    	} else {
    		body = bytes.NewBuffer(make([]byte, 0))
    	}
    	url := &url.URL{
    		Scheme: c.addr.Scheme,
    		Host:   c.addr.Host,
    		User:   c.addr.User,
    		Path:   path.Join(c.addr.Path, requestPath),
    	}
    	req, err := http.NewRequest(method, url.RequestURI(), body)
    	req.Host = url.Host
    	req.URL.User = url.User
    	req.URL.Scheme = url.Scheme
    	req.URL.Host = url.Host
    	req.Header.Set("Content-Type", "application/json")
    	return req, err
    }
    
    Function : Common function to excute the request >>  resp, err := h.c.Do(req)
    
    func (c *Client) Do(req *http.Request, timeout ...time.Duration) (*http.Response, error) {
    	if timeout != nil {
    		c.hc.Timeout = timeout[0]
    	} else {
    		c.hc.Timeout = c.defaultTimeout
    	}
    	return c.hc.Do(req)
    }
    

    Hope this helps .

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    We don't know the Golang. Sorry.

    Task was cancelled

    Please set the log level to Debug and share the request logs. Thanks

    liming.ma@volosoft.com

    public class Program
    {
        public async static Task<int> Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .WriteTo.Async(c => c.File("Logs/logs.txt"))
                .WriteTo.Async(c => c.Console())
                .CreateLogger();
    
  • User Avatar
    0
    Anjaneyulu created

    I got an interesting case here... I could solve the above issue by writing extension to Identity EF core repository. No change in the calling function from the client application.

    public class XSenseEfCoreIdentityUserRepository  : EfCoreIdentityUserRepository, IXSenseIdentityUserRepository
        {
            public XSenseEfCoreIdentityUserRepository(
            IDbContextProvider<IIdentityDbContext> dbContextProvider)
            : base(dbContextProvider)
            {
            }
            
        public virtual async Task<IdentityUser> GetIdentityUserDataAsync(Guid userId)
            {
                var dbContext = await GetDbContextAsync();
                var usersData = await dbContext.Set<IdentityUser>().IncludeDetails(true).Where(u => u.Id ==                                             userId).FirstOrDefaultAsync();
                return usersData;
            }
    }
    

    Now i have different issue with

    idenityUsermanger.UpdateAsync(user)

    Below is the stack trace:

    An unhandled exception has occurred while executing the request.
    System.OperationCanceledException: The operation was canceled.
       at System.Threading.CancellationToken.ThrowOperationCanceledException()
       at System.Threading.CancellationToken.ThrowIfCancellationRequested()
       at Volo.Abp.Identity.IdentityUserStore.GetSecurityStampAsync(IdentityUser user, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.Identity.UserManager`1.GetSecurityStampAsync(TUser user)
       at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
       at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
       at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
       at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
       at Microsoft.AspNetCore.Identity.UserManager`1.ValidateUserAsync(TUser user)
       at Microsoft.AspNetCore.Identity.UserManager`1.UpdateUserAsync(TUser user)
       at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
       at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
       at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
       at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
       at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
       at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
       at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
       at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
       at XSense.Controllers.ComputerController.GetAuthenticationCode(SendAuthenticationRequest request) in D:\Git_Sandbox\XSenseOne\src\XSense.HttpApi\Controllers\ComputerController.cs:line 1207
       at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeInnerFilterAsync&gt;g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextExceptionFilterAsync&gt;g__Awaited|26_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ExceptionContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextResourceFilter&gt;g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeFilterPipelineAsync&gt;g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Logged|17_1(ResourceInvoker invoker)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Logged|17_1(ResourceInvoker invoker)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
       at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Cotur.Abp.ApiKeyAuthorization.Http.ApiKeys.ApiKeyAuthorizationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) in D:\Git_Sandbox\XSenseOne\modules\abp-api-key-authorization\src\Cotur.Abp.ApiKeyAuthorization.AspNetCore\ApiKeys\ApiKeyAuthorizationMiddleware.cs:line 50
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.&lt;&gt;c__DisplayClass6_1.&lt;&lt;UseMiddlewareInterface&gt;b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Builder.ApplicationBuilderAbpOpenIddictMiddlewareExtension.&lt;&gt;c__DisplayClass0_0.&lt;&lt;UseAbpOpenIddictValidation&gt;b__0>d.MoveNext() in D:\Git_Sandbox\XSenseOne\modules\Volo.OpenIddict.Pro\src\Volo.Abp.OpenIddict.AspNetCore\Microsoft\AspNetCore\Builder\ApplicationBuilderAbpOpenIddictMiddlewareExtension.cs:line 21
    --- End of stack trace from previous location ---
       at Volo.Abp.AspNetCore.Uow.AbpUnitOfWorkMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.&lt;&gt;c__DisplayClass6_1.&lt;&lt;UseMiddlewareInterface&gt;b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Volo.Abp.AspNetCore.ExceptionHandling.AbpExceptionHandlingMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Volo.Abp.AspNetCore.ExceptionHandling.AbpExceptionHandlingMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.&lt;&gt;c__DisplayClass6_1.&lt;&lt;UseMiddlewareInterface&gt;b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at XSense.Web.XSenseWebModule.&lt;&gt;c.&lt;&lt;OnApplicationInitialization&gt;b__18_1>d.MoveNext() in D:\Git_Sandbox\XSenseOne\src\XSense.Web\XSenseWebModule.cs:line 562
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
       at Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.&lt;&gt;c__DisplayClass6_1.&lt;&lt;UseMiddlewareInterface&gt;b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.RequestLocalization.AbpRequestLocalizationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.&lt;&gt;c__DisplayClass6_1.&lt;&lt;UseMiddlewareInterface&gt;b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
    

    All the apis are working good earlier, but recently we have to flush the data and after that it seems we are having this issues. I couldnt guess what went wrong.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    The operation was canceled.

    The reason I can think of is that the caller cancels the http request, so the server will have this error.

    HttpContext.RequestAborted

    https://www.meziantou.net/handling-aborted-requests-in-asp-net-core.htm

Made with ❤️ on ABP v8.2.0-preview Updated on March 25, 2024, 15:11