ArxOne / MrAdvice

.NET aspect weaver (build task under NuGet package)
MIT License
308 stars 45 forks source link

How to return response from Aspect? #161

Closed PankajRawat333 closed 4 years ago

PankajRawat333 commented 4 years ago

This is my question not any defect.

I'm trying to develop Authorized aspect for my "AzureFunction". I want to return 401 (UnauthorizedResult) when request header doesn't contain token or invalid token. would like to know how to solve this with aspect?

public async Task Advise(MethodAsyncAdviceContext context) { try { try { HttpRequest request = (HttpRequest)context.Arguments[0]; var tokenString = request.Headers[AnimalHubConstraint.Authorization].ToString().Split(' ')[1]; JwtSecurityToken token = new JwtSecurityTokenHandler().ReadJwtToken(tokenString); var claimPrincipal = GetIdentityFromToken(tokenString); request.HttpContext.User = claimPrincipal; } catch {
return (ActionResult)new UnauthorizedResult(); Error here } await context.ProceedAsync(); // this calls the original method } catch { throw; } }

picrap commented 4 years ago

it’s context.Result = (ActionResult)new UnauthorizedResult()

PankajRawat333 commented 4 years ago

I don't able to find context.Result Instead I found context.ReturnValue

context.ReturnValue = (ActionResult)new UnauthorizedResult(); return;

but this gives me 500 internal server error

picrap commented 4 years ago

ReturnValue is the right property, sorry for mistake. You know have to find what you did wrong in your own code 😉

PankajRawat333 commented 4 years ago

Thanks for confirmation. I'm able to find issue. I was using Async method and IMethodAsyncAdvice Interface in my aspect and I was not returning Task, so I was throwing 500 server error.

context.ReturnValue = Task.FromResult<IActionResult>((ActionResult)new UnauthorizedResult());