How to know if the request is ajax in asp.net in Application_Error()

前端 未结 4 1928
走了就别回头了
走了就别回头了 2021-02-07 19:49

How to know if the request is ajax in asp.net in Application_Error()

I want to handle app error in Application_Error().If the request is ajax and some exception is t

相关标签:
4条回答
  • 2021-02-07 20:21

    it is possible to add custom headers in the client side ajax call. Refer http://forums.asp.net/t/1229399.aspx/1

    Try looking for this header value in the server.

    0 讨论(0)
  • 2021-02-07 20:24

    You could use this.

        private static bool IsAjaxRequest()
        {
            return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
        }
    
    0 讨论(0)
  • 2021-02-07 20:26

    Testing for the request header should work. For example:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult AjaxTest()
        {
            throw new Exception();
        }
    }
    

    and in Application_Error:

    protected void Application_Error()
    {
        bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
        Context.ClearError();
        if (isAjaxCall)
        {
            Context.Response.ContentType = "application/json";
            Context.Response.StatusCode = 200;
            Context.Response.Write(
                new JavaScriptSerializer().Serialize(
                    new { error = "some nasty error occured" }
                )
            );
        }
    
    }
    

    and then send some Ajax request:

    <script type="text/javascript">
        $.get('@Url.Action("AjaxTest", "Home")', function (result) {
            if (result.error) {
                alert(result.error);
            }
        });
    </script>
    
    0 讨论(0)
  • 2021-02-07 20:32

    You can also wrap the Context.Request (of the type HttpRequest) in a HttpRequestWrapper which contains a method IsAjaxRequest.

    bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
    
    0 讨论(0)
提交回复
热议问题