tRuEsAtM
tRuEsAtM

Reputation: 3678

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?

Upvotes: 2

Views: 923

Answers (3)

Abdus Salam Azad
Abdus Salam Azad

Reputation: 5512

You can use like below:

    static async Task<Uri> CreateProductAsync(Product product)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync(
            "api/products", product);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

Detail link from microsoft: Calling a web api

Upvotes: 0

Phong Vo
Phong Vo

Reputation: 1078

You can use WebClient to call your ashx files such as:

WebClient client = new WebClient ();
var content = client.DownloadString("http://yoursite.com/AttachReport.ashx");

Upvotes: 0

Alborz
Alborz

Reputation: 6913

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.

Upvotes: 2

Related Questions