Check session using custom attribute in mvc

 Check session using custom attribute in mvc

In this we will cover how to check session using Action Filter Attribute

1. Custom Attribute
2. Implementation

Custom Action Filter Attribute

public class CheckSessionAttribute : System.Web.Http.Filters.ActionFilterAttribute 
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        HttpContext ctx = HttpContext.Current;
        var userName=HttpContext.Current.Session["UserName"].ToString();            
         string lgnUser = HttpContext.Current.User.Identity.Name;         
         if (string.IsNullOrWhiteSpace(userName) || (userName != "superadmin"))
        {
          var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect,"Your session has expired. Please Click 'OK' to redirect to login page.");
         actionContext.Response = response;
         }
         else
         {                
             base.OnActionExecuting(actionContext);
         }
    }
}

Implementation

[CheckSession]
[RoutePrefix("api/products")]
public class ProductsController : ApiController
    {
        private Product product = new Product();

        [CheckSession]
        [HttpGet, AllowAnonymous, Route("getAllproducts")]
        public HttpResponseMessage GetProducts(int pageNumber = 1, string orderBy = "CreatedOn", string sortingMethod = "DESC", string searchWord = null)
        {
            int organizationID = 0;
            ProductsResponse productsData = new ProductsResponse();
            try
            {
                productsData = product.GetProducts(organizationID, pageNumber, 20 , orderBy, sortingMethod, searchWord);

                if (productsData.Errors.Count == 0)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, productsData);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest, productsData);
        }
}

Post a Comment

0 Comments