We have created a custom attribute in our ASP.Net Core 2.0 WebAPI project for token verification. When the token value is correct the API works well in both
localhostand after publishing. The problem we face is when the token is incorrect, the error message is displayed in
localhostbut it errors on live. It shows error
could not get any responsein postman.
What we should do to display response message from the handler itself?
Here is our code:
usingMicrosoft.AspNetCore.Authorization;usingMicrosoft.AspNetCore.Http;usingNewtonsoft.Json;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingWebCloudPlex.Models.Common;usingWebCouldPlex.Compilers.IntegrationLogic;namespaceWebCloudPlex.Compilers.AuthenticationOptions{publicclass credentialsHandler :AuthorizationHandler<credentialRequirement>{ClsIntegrationObjClsIntegration=newClsIntegration();ResponseMessageObjResponse=newResponseMessage();List<string>ObjListString=newList<string>();privatereadonlyIHttpContextAccessor contextAccessor;public credentialsHandler(IHttpContextAccessor contextAccessor){this.contextAccessor = contextAccessor;}protectedoverrideTaskHandleRequirementAsync(AuthorizationHandlerContext context, credentialRequirement requirement){try{stringAccess_Token= contextAccessor.HttpContext.Request.Headers["Authorization"];ObjResponse.Response="hai";ObjResponse.Status="haiee";stringUserId="1";if(Access_Token!=""){if(UserId!=""&&UserId!=null){if(ObjClsIntegration.CommonTokenVerification(UserId,Access_Token)!=""){ context.Succeed(requirement);}else{ObjResponse=ObjResponse.Get("_1011","Error",ObjListString.Cast<object>().ToList());// below code not working properly in IIS .. its working fine in local host contextAccessor.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(ObjResponse,newJsonSerializerSettings{Formatting=Formatting.Indented})); context.Fail();}}else{ context.Fail();}}else{ context.Fail();}returnTask.CompletedTask;}catch(Exception ex){string filePath =@"Messages\Error.txt";//@"D:\Error.txt";using(StreamWriter writer =newStreamWriter(filePath,true)){ writer.WriteLine("Message :"+ ex.Message+"<br/>"+Environment.NewLine+"StackTrace :"+ ex.StackTrace+""+Environment.NewLine+"Date :"+DateTime.Now.ToString()); writer.WriteLine(Environment.NewLine+"-----------------------------------------------------------------------------"+Environment.NewLine);}throw ex;}}}}