How to call HttpHandler from .cs file asp.net

前端 未结 2 1148
死守一世寂寞
死守一世寂寞 2020-12-31 17:44

I have created a http handler fro my Jquery ajax call. which is working fine the jquery call is mentioned below

 $.ajax({
    url: \"Services/name.ashx\",
           


        
相关标签:
2条回答
  • 2020-12-31 18:23

    You can call any http resource from code behind using HttpWebRequest (System.Net namespace)

    Sample

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create("<YourDomain>/Services/name.ashx?CustMobile=ValueOfA&CustName=ValueOfB&CustEmail=ValueOfC");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    

    You need an absolute path but you can get your domain or server url from the HttpContext if you dont want to hardcode the domain

    More Information

    • MSDN - HttpWebRequest Class
    0 讨论(0)
  • 2020-12-31 18:25

    I found another way of doing this. If you want to access it from the same project it's is very easy.

    Steps to use it in code behind

    1. Basically it create a class with a class name.
    2. You can create a object of that class.
    3. Then you can call ProcessRequest.
    4. It will execute that handler.

    Suppose I have created a handler as follows

    public class HandlerName : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
           //some code
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    

    So you can use it as follows

    HandlerName obj=new HandlerName();
    obj.ProcessRequest(HttpContext);
    

    Note that you can get the current context and you need to pass it in the process request. More about HttpContext [1 2]

    Edit 1

    You can also overload the ProcessRequest method in case if you need to do this.

    public class HandlerName : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
          // some code
        }
        public void ProcessRequest(HttpContext context, string someString)
        {
           // do your coding here
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    

    If you don't want to override the method the you can pass the values as follow
    You can add the value in the HttpContext.Current.Items

    HttpContext.Current.Items["ModuleInfo"] = "Custom Module Info"
    

    and get it as follow in the ProcessRequest Method

    public class HandlerName : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
          string contextData = (string)(HttpContext.Current.Items["ModuleInfo"]);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题