How to capture the url of the page that threw an exception - c#

It's simple enough to grab the current URL with
HttpContext.Current.Request.Url.ToString();
In fact, that's the accepted answer to this very similar question.
However, I've implemented application wide error handling, and have an ErrorController that generates emails that are sent back to us when there is an unhandled exception. If I implement the code snippet above in the Error Controller, the URL I get back is something like
http://.../Error/GenericError?aspxerrorpath=/Controller/ErrorProneAction
How can I grab the url of the page that actually threw the error? That is, something more like
http://.../Controller/ErrorProneAction

According to your comment - do you have a function like void Application_OnError(object sender, EventArgs e) in your global.asax? If so, then you should be able to get the information you are looking for.
protected void Application_OnError(object sender, EventArgs e)
{
var app = (MvcApplication)sender;
var context = app.Context;
string path = context.Request.PathWithQueryString;
...
Gives you something like /controllerOrRoute/action?query=val. Or you can use the RawUrl, or Url property to get basically the same thing. I just fired my application up to see what it generates and it looks like this is what you're asking for.
Edit: I should note that I tested the above for MVC3.

See this blog post:
http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/
If you pass a parameter to your ActionResult, this will take the value of the aspxerrorpath query string value.
public ActionResult NotFound(string url)
{
var originalUri = url ?? Request.QueryString["aspxerrorpath"] ?? Request.Url.OriginalString;
}

Related

Store an URL into a response header so I can access it anywhere

I've searched for hours on this one and didn't find a single answer that worked. Basically what I'm trying to do is the following:
I visit my index page with a set parameters E.G:
http://localhost:51684/Orders/Index?startDate=20%2F05%2F2015&endDate=26%2F05%2F2015
Then i click on an order to go to the Edit View:
http://localhost:51684/Orders/Edit/1400069
I edit some values and i Post: after saving i return to this edit view but my Request.UrlReferrer is: http://localhost:51684/Orders/Edit/1400069 and not the index
A colleague suggested try looking into headers
So I tried doing the following: Add a custom response header at the start so it can be accessed at any time looks something like this:
Code in global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Add("SavedFilters", "/Orders/Index"); //Standard Value
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
And when i apply the filters in the index page i do this:
System.Web.HttpContext.Current.Response.Headers.Set("SavedFilters", Request.RawUrl);
then this happens when I look at the fiddler app:
SavedFilters: /?startDate=20%2F05%2F2015&endDate=26%2F05%2F2015
SavedFilters: /Orders/Index
I get 2 headers with the exact same name...
I'm kinda clueless on what to do/try next so.. any help would be very much appreciated
So you want to send a default header value for "SavedFilters" if you're not specifically setting one in the actual response from the individual web call response?
Simple, change your code in global.asax to:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
if (!HttpContext.Current.Response.Headers.AllKeys.Contains("SavedFilters"))
HttpContext.Current.Response.Headers.Add("SavedFilters", "/Orders/Index"); //Standard Value
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}

Twitter style URLs in asp.net application

I am working on one application it's like twitter.
So how can I accomplish the url such as,
twitter.com/username
This will open profile related to username.
I am creating using asp.net.
Thank you
If you are planning on using MVC Razor, it will be as simple as passing a query string parameter to your page. For example:
public ActionResult Index(string name)
{
//Get user information and pass to view
User userDetails = SomeLogic.GetUser(name);
return View(userDetails);
}
Or, if using ASP.NET Web Forms you will have to use Friendly URL's by adding a Nuget package. Tutorial can be found here: http://blogs.technet.com/b/southasiamvp/archive/2014/03/31/guest-post-exploring-asp-net-friendlyurls.aspx
In the grand scheme of things, all you need to do is pass a query string parameter to your page. Using the friendly URL's will help you accomplish the URL format you require.
Update
From your comment, I see you are using Web Forms, so I will modify the answer on getting a query string value. The code below won't render URL in a friendly format, but I am hoping you will then be able to modify the example based on the link I provided above.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["name"] != null && !String.IsNullOrEmpty(Request.QueryString["name"].ToString())
{
string myNameValue = Request.QueryString["name"].ToString();
//Since you have the name in the querystring, pass value to method that retrieves the record
User userDetails = SomeLogic.GetUser(name);
}
}
So the URL will be: profile.com/profile.aspx?name=John.
But as I stated, you will need to modify the code to change the example to use Friendly URL's, that can be found in this tutorial: http://blogs.technet.com/b/southasiamvp/archive/2014/03/31/guest-post-exploring-asp-net-friendlyurls.aspx

ASP.NET MVC 4 Trigger Error Page

I have been looking for a way to define my own errors in ASP.NET MVC4 using C#. For example, say I have a C# file where I encounter an exception. I would like to trigger the ASP.NET default error page and fill the title and description in with my own error.
To clarify, I am not looking to create a custom error page, as I already know how to do that. Instead, I want to trigger and display my own error message on the default ASP.NET error page. I would like to avoid throwing an exception and never catch it, as I feel that might be a corny way of making ASP.NET choke.
Can anyone show me how I can trigger the error page?
Thank you for your time.
You will get this by adding this into Global.asax file.
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
}
You will get all the details in "currentRouteData" then you can do whatever you want to do with this errors.

Handling Incoming Request URLs in ASP.NET

Currently trying to augment the search of an existing ASP.NET site. My background is Java, so if I was writing a server in Java, I could just handle the incoming request as a string and parse it however I wanted, taking out the search terms, etc.
What part of ASP handles that? Where should I be looking for where the incoming string is taken apart to handle the search request? There is a search button which redirects the page to a URL which includes the search parameters. That's where the trail goes cold for me as I need to know where it comes back into the server.
For example, once you've vetted the search term it gets submitted like this:
Response.Redirect("~/shop?" + type + "=" + searchBoxContent);
'type' is the type of search so that could be based on brand or searching within the product description, etc.
The site is already using some type of url rewriting as the url doesn't show up with any .aspx when you do a search. Should I be looking in a config file or a .master.cs file or where to point me in the right direction?
The easiest system for this is ASP.NET MVC which has a built-in Route and parameter handler.
See MSDN for docs.
Example:
{controller}/{action}/{id}
Can redirect to a Controller action:
public ActionResult Find(int id)
{ ... }
If this is not what you want, take a look at this blog article of Scott Guthrie on URL rewriting.
If you have a URL like this:
/shop.aspx?type=abc
then you can use Request.QueryString the get the value of type. This is the syntax:
Request.QueryString["type"]
For example if you want to get the value when /shop.aspx?type=abc is loaded at the first time, then you should add this code in Page_Load method inside the code behind (shop.aspx.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// assign 'type' query string to typeOfSearch
string typeOfSearch = Request.QueryString["type"];
}
}

Getting client ip address in Global.asax.cs - is it possible?

Of course that Request.UserHostAddress way is great, however in Application_Start() the Request object isn't exists yet.
I want to first guess the location of user by his/her IP - just one time - as he/she enters the web site, and set the default locale for him/her. Then I'll manipulate it some where else.
I think that there must be an event to be overridden in Global.asax which Request exists in it, However I can't find that event...
Indeed any alternate trick will be appreciated...
Update:
In fact, I'm developing a multilingual web site and I use MaxMind GeoIP to get the country of users by their IP. So, I want to find a way in order that when a user enters the site (only and only the first request) I retrieve his/her country and store it in Session or a global variable.
I know that I can achieve my goal any where else by Request.UserHostAddress and I have not any problem with it - just one line overhead for each request isn't an issue at all for this small app.
However I wonder if it is possible to set that global variable, only and only once...!?!
Application_Start() is not right event, in which you can do this. It will not run for every request from your user, it does some basic initialization of asp.net application.
Better solution is to user, for example
protected void Application_BeginRequest(){}
which runs on beginning of request from client.
About earliest event, in which both request and session will be available... Seems like it is
void Application_AcquireRequestState(object sender, EventArgs e)
{
if (System.Web.HttpContext.Current.Session != null)
{
if (Session["locale"] != null)
{
//already set variable.
}
else
{
//set some variable
Session["locale"] = "code";
}
}
}
But what exactly do you want to you mean by "setting locale based on IP"? Can you clarify this task? 'Cause in general, for each request execution this "locale" information must be set.
You should do this like this
public void Init(HttpApplication context)
{
context.BeginRequest += (Application_BeginRequest);
}
private void Application_BeginRequest(object source, EventArgs e)
{
var context = ((HttpApplication) source).Context;
var ipAddress = context.Request.UserHostAddress;
}
It may be solved by using GlobalFilterCollection. You can override the method OnActionExecuting and add the necessary logic. This article: ASP.NET MVC 4 Custom Action Filters may help.

Categories

Resources