skip to Main Content

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?

3

Answers


  1. 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.

    Login or Signup to reply.
  2. You can use WebClient to call your ashx files such as:

    WebClient client = new WebClient ();
    var content = client.DownloadString("http://yoursite.com/AttachReport.ashx");
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search