简体   繁体   English

C'# 检查 Ajax 是否调用 c# 端

[英]C'# Checking if an Ajax call c# side

I have some code below so that when a user calls a method in an mvc controller it does some checks to see if it is an Ajax call or not.我在下面有一些代码,这样当用户调用 mvc controller 中的方法时,它会进行一些检查以查看它是否是 Ajax 调用。 If Ajax it returns a json response else it returns a url string (Security page).如果 Ajax 返回 json 响应,否则返回 url 字符串(安全页面)。 When I run in visual studio the code works perfectly so it recognises the call is an ajax call but on a production server variable "isAjax" is set to false.当我在 visual studio 中运行时,代码运行良好,因此它识别出调用是 ajax 调用,但在生产服务器上变量“isAjax”设置为 false。 Is there any reason why it would work locally in visual (local iis) but not on a server?有什么理由可以在视觉(本地 iis)中本地工作,但不能在服务器上工作?

var isAjax = (filterContext.RequestContext.HttpContext.Request["X-Requested-With"] == "XMLHttpRequest") ||
                             ((filterContext.RequestContext.HttpContext.Request.Headers != null) &&
                             (filterContext.RequestContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

On the.network tab in the browser it shows that it is being passed (image below)在浏览器的 .network 选项卡上显示它正在通过(下图)

Network tab网络选项卡

public ActionResult GetData()
{
  if(Request.IsAjaxRequest())
        return RedirectToAction("AjaxRequest");
  else
        return RedirectToAction("NonAjaxRequest");
}

Instead of checking the headers you can check the current request at controller level.您可以在 controller 级别检查当前请求,而不是检查标头。

AJAX calls will have a header named X-Requested-With , and the value will be XMLHttpRequest . AJAX 调用将有一个名为X-Requested-With的 header,其值为XMLHttpRequest So you can check like this:所以你可以这样检查:

bool isAjaxRequest = request.Headers["X-Requested-With"] == "XMLHttpRequest";

Otherwise you can use the System.Web.MVC reference and use the function.否则,您可以使用System.Web.MVC参考并使用 function。

bool isAjaxRequest = Request.IsAjaxRequest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM