asp.net mvc: how to detect when a page is called using ajax

后端 未结 6 1849
遥遥无期
遥遥无期 2021-02-12 20:26

how to detect when a page is called using ajax in asp.net mvc ?

6条回答
  •  清酒与你
    2021-02-12 20:56

    The best way to check if the request is an ajax request is to check Request.IsAjaxRequest(). It's good to know that under the hood, MVC framework checks for ajax requests in the Request Parameters OR the Request Header. The code in ASP.Net MVC source code is:

        public static bool IsAjaxRequest(this HttpRequestBase request) {
            if (request == null) {
                throw new ArgumentNullException("request");
            }
    
            return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
        }
    

    So if you want to check it mannually (which is not recommended) you have to check both.

提交回复
热议问题