How can i catch parameter on maproute? - asp.net-mvc

How can i retrieve certain a section on routemap pattern.For instance i have a routemap pattern on my config file as routes.MapRoute("", "Post/{slug}", new { controller = "Post", action = "Index" }) and i want to catch slug parameter inside global.asax.I tried as followed but it returns null.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = base.Context;
if (context != null)
{
Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
}
}

You can try this:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
if (currentRouteData.Values["slug"] != null)
{
Response.Write(currentRouteData.Values["slug"]);
}
}

I believe RouteData is not yet resolved when BeginRequest event is fired. You can use EndRequest instead.
protected void Application_EndRequest(object sender, EventArgs e)
{
var context = base.Context;
if (context != null)
{
Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
}
}
To make sure correct route is being used and slug parameter is actually supplied I'd recommend Route debugger

Related

Is there any way where I can set user information into Session values from cookies while rendering a controller in MVC?

I have tried in Global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
var cookiesDataUserinfo = HttpContext.Current.Request.Cookies["UserInfo"];
if (cookiesDataUserinfo != null)
{
Session["UserId"] = cookiesDataUserinfo["UserId"].ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
But I am getting the error "Session state is not available in this context."
I also tried to load data from cookies in constructor of a controller. But cookies is null inside constructor.
Is there any way where I can set session values from cookies before any view is rendered in my MVC project?
I have found the solution I was looking for. I need to use the Application_AcquireRequestState method in Global.asax.cs
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
try
{
var cookiesDataUserinfo = HttpContext.Current.Request.Cookies["UserInfo"];
if (cookiesDataUserinfo != null)
{
Session["UserId"] = cookiesDataUserinfo["UserId"].ToString();
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
For every request the Application_AcquireRequestState method is called and I can set session values from Cookies if available.

How to catch unhandled errors in ASP.NET MVC?

I've created a simple MVC project, add one method:
public class HomeController : Controller
{
public async Task<string> Index()
{
var t = Task.Run(() =>
{
Debug.Print("Debug___1");
throw new Exception("Error #1");
Debug.Print("Debug___2");
});
await Task.Delay(5000);
return "ASD";
}
}
Then i run application, get "ASD" output and debug messages:
Debug___1
Exception thrown: 'System.Exception' in WebApplication2.dll
But how can I catch that exception? I've tried creating Application_Error method on global.asas, but it didn't work:
namespace WebApplication2
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
Debug.Print("Catched");
}
}
}
At the controller level, you can deal with unhandled exceptions by overriding the OnException method.
Look at this link for a description: https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine
catch(Exception ex)
{
//create custom error handling method
ErrorLog(ex);
}
Public static void Errorlog(Exception ex)
{
//creates new txt file to view errordetails
string strPath = #"D:\ErrorLog.txt";
File.create(strPath);
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("Error Details",+DateTime.Now);
sw.WriteLine("Error Message: " + ex.Message);
sw.WriteLine("Stack Trace: " + ex.StackTrace);
}
}
.NET 4 allows you to define how your task will handle exceptions as shown in the following post : catch exception that is thrown in different thread
So in your example above, you would first define your task
Task<string> task = new Task<string>(Test);
then pass in an exception handler
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
then finally define an exception handler somewhere
static void ExceptionHandler(Task<string> task)
{
var exception = task.Exception;
//Handle error via ModelState or how you prefer
}
Use the HttpServerUtility.HttpApplication.Server object's method GetLastError.
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
}

I cant access to HttpContext.Application It always return null

this is my code for counting online users
it works well in global.asax and it count well
but when I call it from controller it returns null
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
protected void Application_Start()
{
Application["OnlineUsers"] = 0;
}
in controller:
string strUsersOnline = HttpContext.Application["OnlineUsers"] as string;
ViewData["OnlineUsers"] = strUsersOnline;
The value is null because the of the as keyword, use explicit conversion or .ToString()
Refer MSDN

Global.asax in Umbraco 6

I had the following in my Global.asax (Umbraco 4.7)
Application_Start
Application_EndRequest
Application_Error
Session_Start
Session_End
Now I have upgraded to Umbraco 6.0.3, which global.asax inherits from Umbraco.Web.UmbracoApplication
Where do I put my event handlers (and what are the equivalent method names)?
This is what I found so far.
You can create your own class
public class Global : Umbraco.Web.UmbracoApplication
{
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);
application.EndRequest += (new EventHandler(this.Application_EndRequest));
//application.Error += new EventHandler(Application_Error); // Overriding this below
}
protected override void OnApplicationStarted(object sender, EventArgs e)
{
base.OnApplicationStarted(sender, e);
// Your code here
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
try
{
if (Session != null && Session.IsNewSession)
{
// Your code here
}
}
catch(Exception ex) { }
}
private void Application_BeginRequest(object sender, EventArgs e)
{
try { UmbracoFunctions.RenderCustomTree(typeof(CustomTree_Manage), "manage"); }
catch { }
}
private void Application_EndRequest(object sender, EventArgs e)
{
// Your code here
}
protected new void Application_Error(object sender, EventArgs e)
{
// Your error handling here
}
}
And have Global.asax inherit from your class
<%# Application Codebehind="Global.asax.cs" Inherits="Global" Language="C#" %>
Alternative method: Inherit ApplicationEventHandler - but it's not working for me

Session being cleared in ASP.NET MVC

What happens to Session between the Session_Start call and OnActionExecuting in an ActionFilterAttribute.
For some reason, when I set something like this:
protected void Session_Start(object sender, EventArgs e)
{
Session["GoToBuyPage"] = true;
}
and try to access it here in the ActionFilterAttribute:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool goToPage = (bool)Session["GoToBuyPage"];
it is always null. Any ideas why?
There's no Session property of an ActionFilterAttribute. So I don't even know how your code compiles. The following works perfectly fine for me:
Action filter:
public class FooAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool goToPage = (bool)filterContext.HttpContext.Session["GoToBuyPage"];
filterContext.Result = new ContentResult
{
Content = goToPage.ToString()
};
}
}
Controller:
public class HomeController : Controller
{
[Foo]
public ActionResult Index()
{
return View();
}
}
Session_Start:
protected void Session_Start(object sender, EventArgs e)
{
Session["GoToBuyPage"] = true;
}

Resources