ASP.Net: Create handler within project - asp.net

Sorry if this is a stupid question. I want to create an HTTP handler within my project. To do this, I created a new class, and tried to implement IHttpHandler.
Each time I do this, I get the error 'End of statement expected'.
I know that normally you can create a new class library and create a class to implement a handler. But why is it not possible to do this in an existing web project?
WT

Create a new object called an ashx or Generic Handler. From there you can put in server side code and output the exact result you would like to dish out. Honestly though I would use WCF though, its a lot easier and you can spit out the data in any data type you like.

Even though its not a best practice to put it in the web project, are you referencing it in the web.config correctly, so it knows to look in the App_Code folder?
<httpHandlers>
<add verb="*" path="*.yourextention" type="YourHandler, App_Code"/>
</httpHandlers>

Related

Something is seriously wrong with my ASP.NET MVC

I have been programming ASP.NET Web Forms for a long time and recently decided to learn ASP.NET MVC.
However, I am clearly having some issues that I cannot tell how. No one that I have come across in web had the same problems.
#1: Web.config issues
When I first created my MVC project in VS2019, there was no web.config so I added it via project > add new item> Web Configuration File.
All I needed it for was to store my connection string. When added it had only two lines of code:
<configuration>
</configuration>
I added my connection string and the file looked like this:
<configuration>
<connectionStrings>
<add name="connection" connectionString="myconnectionstringblablabla" />
</connectionStrings>
</configuration>
In my controller I tried to fetch the connection string by doing,
string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
And this happened:
Same things happens when fethcing AppSetting keys from web.config.
Is web.config not meant to be used for ASP.NET MVC?
#2 Global.asax
Unlike web.config, Global.asax file doesn't even show up on the add new item menu:
Tried this solution: How to add a Global.asax file to ASP.NET MVC5 project Didnt work either.
#3 Session & HttpContext
In ASP.NET Web.Forms, I would normally use Session variables like this:
Session["ClientID"] = somevalue;
I can't do that in ASP.NET MVC, although I have seen people doing it.
Also I can't access to HttpContext from a non-controller class:
HttpContext.Current.Request.Cookies["mycookie"];
It throws HttpContext does not contain a definition for 'Current'...
====================================
Is Something wrong with my program. I don't know how to check if I am using correct references or assemblies, but I think I am missing something.
Please help

Can custom IHttpHandler revert to default request handling?

I'm writing a custom HttpHandler to process web requests for a web framework I'm writing but trying to find a way to programatically "ignore" the request if no url route is matched. What I mean by ignore is if no predefined route matches the incoming request url to then default to the standard request processing you would get if you were using a raw ASP.Net web application.
The only way I can find that actually works so far is to remove the custom http handler for a specific path, e.g.:
<location path="Test">
<system.webServer>
<handlers>
<remove name="DefaultHandler"/>
</handlers>
</system.webServer>
</location>
I'm not massively satisfyed with this solution and would like to implement something akin to MVC's IgnoreRoute("..."). Digging through ths source though is a bit of a thankless task and I can't see where it's actually doing it.
So ideally I'd like to know if it's possible to somehow exit the custom http handler and let the application handle it in a default manner or find out how MVC does this.
Anyone have any ideas?
Thanks.
I don't think you can do it in an Httphandler.
Consider using an HttpModule. This is also how MCV routing works.

What's the difference between making a handler w/ ashx/axd and using something I made up myself in ASP.NET?

This is probably very simple but it's really confusing me. When I implement the IHttpHandler, I create a handler and then register it like so in the web.config:
IIS6 Portion:
<httpHandlers>
<add verb="*" path="*.randomextension" type="MyProgramNameSpace.MyHandler" />
</httpHandlers>
IIS7 Portion:
<handlers>
<add name="mine" verb="*" path="*. randomextension" type ="MyProgramNameSpace.MyHandler" />
</handlers>
It seems to work quite well and get to use different handlers and options for it. It let's me skip the Page class and so forth by directly accessing the pipeline. However, every so often I keep running into documentation where it says I need to use something about ashx or axd with something.
What is all this about? How does this have to do w/ handler creations?
This is probably very easy but for some reason I'm completely confused when going about this ashx or axd handler.
The .asxh handler is simply a pre-existing/pre-defined generic handler mapping. Unlike the .aspx handler, you are not restricted to deriving from Page, and you don't get the full ASP.NET page handler event pipeline. Generally, you use .ashx files to handle non-page requests that take as input or return as output non-standard content.
The different from an .ashx handler and a custom IHttpHandler is not much, really. A lot of configuration is predefined for .ashx files, but, you are bound to that extension. With a full custom IHttpHandler, you have complete and total freedom, but need to configure it from the ground up.
There really isn't a difference. .ashx files implement IHttpHandler just like you are doing. Only .ashx is a pre-registered handler so you don't need to add it to the web.config yourself it's already done for you.
If you are deciding to use the extension by file type your handler is appropriate.
If on the other hand, you are trying to return data, without a particular extension, the ashx/ahd extension is just as good.
For example, if you have a collection of images stored in a database, you could register a .JPG handler, that would pull the image from the database instead of the hard drive. You could also create an ASHX that could return any image type.
Registering an extension could make the url look more "normal" to the end user, while an ashx looks more generic (even geeky).

Something faster than HttpHandlers?

What is the fastest way to execute a method on an ASP.NET website?
The scenario is pretty simple: I have a method which should be executed when a web page is hit. Nothing else is happening on the page, the only rendered output is a "done" message. I want the processing to be as fast as possible.
Every single hit is unique, so caching is not an option.
My plan is to use an HttpHandler and configure it in web.config (mypage.ashx) rather than a regular .aspx page. This should reduce the overhead significantly.
So my question is really: Is there a faster way to accomplish this than using HttpHandlers?
Depending on what you're doing, I wouldn't expect to see a lot of improvement over just using an HttpHandler. I'd start by just writing the HttpHandler and seeing how it performs. If you need it to be faster, try looking more closely at the things you're actually doing while processing the request and seeing what can be optimized. For example, if you're doing any logging to a database, try writing to a local database instead of across a network. If it's still not fast enough, then maybe look into writing something lower level. Until that point though, I'd stick with whatever's easiest for you to write.
For reference, I've written an ad server in ASP.NET (using HttpHandlers) that can serve an ad (including targeting and logging the impression to a local database) in 0-15ms under load. I thought I was doing quite a bit of processing - but that's a pretty good response time IMHO.
Update after several months:
If you clear all the HttpModules that are included by default, this will remove a fair amount of overhead. By default, the following HttpModules are included in every site via the machine-level web.config file:
OutputCache
Session (for session state)
WindowsAuthentication
FormsAuthentication
PassportAuthentication
RoleManager
UrlAuthorization
FileAuthorization
AnonymousIdentification
Profile
ErrorHandler
ServiceModel
Like I said above, my ad server doesn't use any of these, so I've just done this in that app's web.config:
<httpModules>
<clear />
</httpModules>
If you need some of those, but not all, you can remove the ones you don't need:
<httpModules>
<remove name="PassportAuthentication" />
<remove name="Session" />
</httpModules>
ASP.NET MVC Note: ASP.NET MVC requires the session state module unless you do something specific to workaround it. See this question for more information: How can I disable session state in ASP.NET MVC?
Update for IIS7: Unfortunately, things aren't quite as simple in IIS7. Here is how to clear HTTP Modules in IIS7
I'm not sure what your exact scenario is, but if all your page is doing is processing some data, you don't really need an aspx page or an http handler at all. You could write an ASMX web service or WCF service to do what you need and this would most likely be less overhead. The WCF service doesn't even have to be hosted in ASP.NET. You can host it from a Windows service or console app, and call it in-proc using named pipes. This would probably reduce the overhead for calling the data processing code significantly.
If you really have to use asp.net, you can also just hook into AuthorizeRequest step and intercept the request from there, do your processing and write your Done response directly.

Creating a web service without an ASMX file?

I have written an ASP.NET composite control which includes some Javascript which communicates with a web service.
I have packaged the classes for the control and the service into a DLL to make it nice and easy for people to use it in other projects.
The problem I'm having is that as well as referencing the DLL in their project, the consumer of my control must also include a .ASMX file for the web service. Whilst it isn't a complicated file (just a one-liner which refers to the class in the DLL), I would like to avoid having it if I can.
Is there any way to avoid having to have the .ASMX file?
Can I register the service with the web server in Application_Start?
Can I make a web.config change to reference it somehow?
All suggestions gratefully received!
UPDATE: The article linked to in John Sheehan's response (below) does work - but not if you want to call the web service using AJAX. Does anybody know of an AJAX friendly version?
Try something like this. I don't know if it will work though. I got this idea from ELMAH, which creates a handler for a page that doesn't physically exist and then serves it up from the assembly.
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*WebService.asmx" type="MyHandler.WebServiceHandler, MyHandler" />
</httpHandlers>
</system.web>
</configuration>
EDIT: I was close, see this article (in VB though): http://www.codeproject.com/KB/aspnet/wsinaclasslibrary.aspx
I know this is very old question, but it hasn't been answered properly, so here it is:
Every *.ASMX request is by default handled by System.Web.Services.Protocols.WebServiceHandlerFactory.
Looking into source code of this class in .NET reflector, it's possible to have webservice without ASMX file but you will need to call internal method CoreGetHandler through reflection.
Following method will take your webservice and return its IHttpHandler.
public IHttpHandler GetHttpHandlerForWebService(WebService webService, HttpContext context)
{
var webServiceType = webService.GetType();
var wshf = new System.Web.Services.Protocols.WebServiceHandlerFactory();
var coreGetHandler = wshf.GetType().GetMethod("CoreGetHandler");
var httpHandler = (IHttpHandler)coreGetHandler.Invoke(wshf, new object[] { webServiceType, context, context.Request, context.Response });
return httpHandler;
}
Once you have your httphandler, it's just matter of calling
httpHandler.ProcessRequest(context)
Done. No ASMX and no web.config entries.
Here is a very good working article about your problem:
Creating Web Services in a Class Library project on Codeproject.
Consider trying page methods (see this blog post). All you have to do is add the web method attribute to a static method in the aspx code behind. Then access the PageMethod object from your clientside code (javascript). No ASMX files needed. Hope this helps.
Short answer is no. The ASMX is the entry point for any web service. There are alternatives if you use WCF, but that's not entirely the same thing.

Resources