.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Post New Web Links

Intercept ActionResult (specifically when a HttpUnauthorizedResult() is set in OnAuthorization)

Posted By:      Posted Date: September 08, 2010    Points: 0   Category :ASP.Net
Hello everyone, I have a custom Authorize attribute, which implements OnAuthorization. In the default OnAuthorization, an HttpUnauthorizedResult is set when there is an authorization failure. Can I intercept this ActionResult somewhere and take a specific action based on it. I do not want to put all the redirection logic etc. in OnAuthorization? Kind regards,    Edwin.

View Complete Post

More Related Resource Links

ASP.NET: Intercept, Monitor, and Modify Web Requests with HTTP Filters in ISAPI and ASP.NET


There can be many reasons to reroute incoming Web requests. For instance, sometimes it's necessary to redirect a browser to a page based on user criteria without passing long lists of parameters in the URL. In the past, the only way to intercept such page requests and send them elsewhere was with ISAPI. Now, in ASP.NET, the IHttpModule interface provides notification of server requests, and lets you easily reroute them based on criteria other than browser type or version. Here the author demonstrates the use of IHttpModule for interception and explains the use of ISAPI filters for anyone who isn't yet using ASP.NET.

Panos Kougiouris

MSDN Magazine August 2002

Action method returning an ActionResult used in a Action method


Hell all,

I have the Index action method calling a method that itself is an action method.

Example :

public ActionResult Index()
   //do stuff
   ActionResult result = MethodB();
   // ?? what to return here ??

public ActionResult MethodB()
   //do stuff

  return View("Index);

What to do in this case ?

How to specifically sort the data in a database using c#?

<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:TrackMoves/> <w:TrackFormatting/> <w:PunctuationKerning/> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:DoNotPromoteQF/> <w:LidThemeOther>EN-US</w:LidThemeOther> <w:LidThemeAsian>X-NONE</w:LidThemeAsian> <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript> <w:Compatibility> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:SplitPgBreakAndParaMark/> <w:DontVertAlignCellWithSp/> <w:DontBreakConstrainedForcedTables/> <w:DontVertAlignInTxbx/> <w:Word11KerningPairs/> <w:CachedColBalance/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> <m:mathPr> <m:mathFont m:val="Cambria Math"/> <m:brkBin m:val="before"/> <m:brkBinSub m:val="--"/> <m:smallFrac m:val="off"/> <m:dispDef/> <m:lMargin m:val="0"/> <m:rMargin m:val="0"

Calc'd Member Specifically for JAN, FEB etc of Chosen Tran Date

Hi.  I'd like to display same year calc'd measures [January Completions], [February Completions] ...[December Completions] next to the [Actual Completions] measure for transaction year x, transaction month y. If y is January then [January Completions] thru [December Completions] need to be overridden with zeros.  If y is February, Feb thru Dec need to be overridden with zeros and so on. I started experimenting with the query you see below before transferring the logic to my cube.  I didnt even get to the if/then logic before I saw that April and beyond of each year's [January Completions] was null.  But the correct/same Jan amount showed next to the 1st 3 [Actual Completions] for 2009 and 2010 which are the only years I've loaded at this point. [Actual Completions] itself is a calc'd measure from two different measure groups that share most dims including transaction date.  I dragged the hierarchical month name to the "on rows" clause.  I had no luck mixing hierarchical names with the currentmember function in the "with" clause so I dragged the non hierarchical tran date names there.  What am I doing wrong? with member [Overall Jan Completions This Year] as ([Measures].[Actual Completions], [Date Transaction].[Year].   Currentmember,   select {([Measures].[Actual Com

Intercept Check-In Event of Document Library in SharePoint 2010

we need to intercept the default check-in Event of the Document Library. The detailed requirements is as follows.   1. Intercept the check-in Event of Document Library. 2. Instead of the default check-in  page (normally this is the layout's checkin.aspx page), show our custom application page. 3. In the custom application page, allow users to provide some inputs. Validate the input values against values stored in database. 4. Once validated successfully, allow user to check-in the documents. Else, do not allow user to check-in the document.   One more additional requirement is the above things should happen only for our custom content type. In order to achieve the same, we are planning for deploying our custom document content types and perform the above operations on check-in event of the documents.     Another approach of performing the same is , have our own custom ECB Menu. The detailed process is as below.   a. Customize the check in menu (ECB) b. Show the custom form and get the inputs from user and do the validations c. On the OK button click, if validation is success, then update the meta data and check in the document or deny the process. d. But in this approach, we need to check the libraries version settings and that default functionalities should be added automatically to the check in process.   At this point of time, we a

ActionResult to appear in new window

Ok, our implementation of an mvc site is being done in a very weird way but none the less it is still mvc.I have an issue that on a certain page, when you click a button to download a document, it retrieves from a web service a byte array of a document. This is not an issue as i pass this byte array into the view data to allow me to access it in our controller.This is the code in the controller.if (ViewData["FileDownloadData"] != null) { action = GetFile((Byte[])ModelState["FileDownload"].Value.RawValue, ViewData["FileDownloadData"].ToString()); }now the get file method is as suchpublic FileStreamResult GetFile(Byte[] fileBytes, String mimeType) { if (ViewData["FileDownloadData"] != null) { ViewData["FileDownloadData"] = null; } Stream fileStream = new MemoryStream(fileBytes); return new FileStreamResult(fileStream, mimeType); }Now this all works ok but as expected the result is rendered out into the current window. Is there anyway at all i can trigger a new window to render out the document?Cheers

how can i return 401 error from a method return ActionResult?


how can i return   401 error from a method return ActionResult?

n-tier, configuration info, specifically connection strings



I have an ASP.NET project which is pretty n-tier, by namespace, but I need to separate into three projects:  Data Layer, Middle Tier and Front End.

I am doing this because... 

A) It seems the right thing to do, and

B) I am having all sorts of problems running unit tests for ASP.NET hosted assemblies.

Anyway, my question is, where do you keep your config info?

Right now, for example, my middle tier classes (which uses Linq to SQL) automatically pull their connection string information from the web.config when instantiating a new data context.

If my data layer is in another project can/should it be using the web.config for configuration info?

If so, how will a unit test, (typically in a separate assembly) provide soch configuration info?

Thank you for your time!


Textbox - how to intercept special characters ?


I need to handle keypress Ctrl-1..9 and Alt1..9 when the focus is in a TextBox.

I have tried PreviewKeyDown on both the form and the derived TextBox class, but neither get called in the case of special characters.

I see one solution is to create and attach a routed command per key, but I'm wondering if there is any other way to do this?

Poorly formed JSON from MVC 2 actionresult



I created an MVC 2 action which is supposed to return JSON.

When i verified the output in jsonlint.com, the result was 'invalid JSON'

The code used was;

        public ActionResult MarketList()
            var mkt = db.GetDailyList();
            return Json(mkt, JsonRequestBehavior.AllowGet);

Is this correct?

I also noticed that when i pasted the raw JSON feed from the URL into the jsonlint.com textbox, it was valid.

What could be going on here?


Intercept manual refresh in inserting db action page


Hello...i have a e-commerce page which send data to last page for the payment...

In this last page, the user confirm his intention to acquire products .... In this moment, i've created a sub which insert a new order in the database...all works!...

The problem born when i try (and user could too) to manually refresh the page...the code will be processed again and a new (second) order will be inserted in the database.....it's not correct...

This page make a postback after confirm button....so control page.ispostback will not resolve problem...

How could i intercept manual refresh of this page in a secure way ?

Thanks to allUndecided

Intercept (and process) httpcontext.current.cache methods


Anyone know of a way (and how) I can intercept calls to the httpcontext.current.cache methods so that I can do some extra processing?

For example, when someone calls:

httpContext.Current.Cache.Add("some key", objSomeObject, Nothing, System.DateTime.Now.AddMinutes(63), Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
I want to be able to Intercept that call and find out:
1. What the "some key" value was AND
2. What the expiration value was.
All without having to filter through tons of code and change the calls.
PLUS, I don't want to have to rely on various developers compliance with inserting a call to
the tracking routine: if they use Cache.Add, my code gets called and I know what was passed.

How to intercept an Excel PivotTable call result from an SSAS cube?


We have a SSAS Cube (2008 R2) on a server, which end-users are viewing with Excel 2010’s PivotTable interface.

We now want to stop end-users dynamically from drilling down to sensitive data.

Specifically, we want to dynamically block the return of any pivot table in which any element has a count of less than k  (and ideally: an error to be displayed ‘query results would return sensitive data – please modify your query’)

This feature should be implemented on the server-side cube not at the level individual end-user's Excel (e.g., Excel add-in).


How to intercept the raw XML messages of a WCF client using WS security???


Hi there,

I've set up a WCF service using WS-Security. I've also implemented an according test client. For testing purposes it's often important to know how the raw XML looks like, that has been sent to the service or that was replied from it.

What I've done so far is the following. I created a special message inspector:

public class MessageViewerInspector : IEndpointBehavior, IClientMessageInspector
	#region Properties

	public string RequestMessage { get; set; }
	public string ResponseMessage { get; set; }

	#region IEndpointBehavior Members
	public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)


	public void ApplyClientBehavior(ServiceEndpoint

Does an iFilter need to be written specifically for SharePoint or Windows Server?


I have an iFilter for a memory map type piece of software.  The iFilter works in 64-bit versions of Windows 7 and I was hoping to get it working with SharePoint.

The iFilter consists of a dll that is registered with regsvr32 manually and another helper dll (not sure what this does exactly). 

I registered the dll on the windows server machine (single machine with server 2008R2 and SharePoint server 2010).  I followed the same steps that are used to install the pdf iFilter - I put in a registry key for the file extension at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension\ and gave it's default value the CLSID of the iFilter.  (If you've read the guides for sharepoint 2010 and pdf ifilter hopefully you understand this)

This doesn't work.  The pdf iFilter works, and when I do a crawl of the sharepoint sites I can see that the adobe ifilter DLLs are being used.  My mind map dll filter dll is not being used.

Has anyone got any guidance on custom iFilters with SharePoint 2010?

How to intercept mail messages before reaching a SMTP server


I need an application that will intercept all incoming mail messages and modify them according to some specs. I am an absolute rookie at this, please detail :)

a)     I need to either hook into it's SMTP events, and modify the message before it is passed on to the local intended user.


b)    A SMTP proxy service, that sits in front of your real SMTP server. Inside of the SMTP proxy,

HELP: Creating an ActionResult method to display a particular database record using Entity Framework


Hi All,

I have an ActionResult method that displays records from a database table (below):

namespace STD.Controllers
    public class StudentController: Controller
        StudentEntities stud;
        public StudentController()
        stud= new StudentEntities ();


        public ActionResult Index()
            ViewData.Model = stud.StudentTable.ToList();
            return View();


I want to design a method "ActionResult Student()" that accepts "Student ID" as a parameter and displays record for that particular student only.

What do I need to do to make this happen? Could anyone please help me with this?

Thanks in advance


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend