Search code examples
c#asp.netasp.net-web-apiashx

Is it possible to reuse/call a handler in C# Website from C# WebApi?


I have an ASP.NET website that contains a number of handlers (.ashx). Is it possible to call that handler from a standalone C# REST API (Web API)? Or does it need to be in the same solution file?

enter image description here

For example, my handler file contains the following code

public override void ProcessRequest(HttpContext context)
        {

            base.ProcessRequest(context);
            context.Response.ContentType = "text/xml;charset=utf-8";
            try
            {
                string action = context.Request["action"] ?? "";
                switch (action.ToUpper())
                {
                    case GETDATA:
                        GetDataActions(context);
                        break;

                    case SETDATA:
                        SetDataActions(context);
                        break;
                    default:
                        throw new Exception("");
                }
            }
            catch (Exception genericException)
            {
                context.Response.StatusCode = 500;
                WriteResponse(context, xError.ToString());
            }
        }

I would like to call SETDATA action from my WEB API controller. Can anyone guide me?


Solution

  • You can reuse the handlers by calling them like a WebApi.

    Make sure you have configured the handlers in your .config file and define a routing for them.

    <httpHandlers>
        <add verb="[verb list]" path="[path/wildcard]" type="[COM+ Class], [Assembly]" validate="[true/false]" />
        <remove verb="[verb list]" path="[path/wildcard]" />
        <clear />
    </httpHandlers>
    

    Find more info here https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/aspnet/development/http-modules-handlers

    ANOTHER OPTION: You can reuse the handlers by packaging them as a library then use it in different projects. A nugget package for example.