Tuesday 26 March 2019

redirect from action filter to another action method in mvc


Step1: create your action attribute

public class RedirectCustomFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
             // // Way-1
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "About" }));
            //filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);

            //// Way-2
            //var controller = (HomeController)filterContext.Controller;
            //filterContext.Result = controller.RedirectToAction("about", "home");

            ////base.OnActionExecuting(filterContext);
        }


Not If you wat to go with Way-2 then you need to create a method inside your controller

  public class HomeController : Controller
    {
        public new RedirectToRouteResult RedirectToAction(string action, string controller)
        {
            return base.RedirectToAction(action, controller);
        }
        [RedirectCustomFilter]
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

Wednesday 20 March 2019

Await in Catch and Finally blocks

Await in Catch and Finally blocks is a part of C# 6.0

 public static async Task<string> Test()
        {
            await logMethodEntrance();
            var client = new System.Net.Http.HttpClient();
            var streamTask = client.GetStringAsync("https://localHost:1234");
            try
            {
                var responseText = await streamTask;
                return responseText;
            }
            catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("401"))
            {
                await logError("test your accessbility", e);
                return "not applicable";
            }
            finally
            {
                await logMethodExit();
                client.Dispose();
            }
        }
        private static Task logError(string v, HttpRequestException e)
        {
            throw new NotImplementedException();
        }
        private static Task logMethodExit()
        {
            throw new NotImplementedException();
        }
        private static Task logMethodEntrance()
        {
            throw new NotImplementedException();
        }