2

I've tried the following in my C# Controller

used the following namespaces

 using System;
 using System.Web;
 using System.Web.Mvc;

and the following "things" inside IActionResult Create() method

    // GET: Movies/Create
    public IActionResult Create()
    {
        Request.IsAjaxRequest(); // this line tells me "HttpRequest does not contain a defintion for IsAjaxRequest .. (are you missing a using directive?)"


        string method = HttpContext.Request.Method;
        string requestedWith = HttpContext.Request.Headers["X-Requested-With"];

        HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";

        new HttpRequestWrapper(System.Web.HttpContext.Current.Request).IsAjaxRequest()


        return View();
    }

None of them works for me. I can debug the request but I can not find anything telling me this is a xhr or XMLHttpRequest.

I'm calling the controller action like so:

function reqListener () {
    console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://localhost:5001/Movies/Create");
oReq.send();

The browser dev tools tell me it is a XHR Type Request: enter image description here

How can I detect the XHR request in a C# Controller or in a .cshtml file?

caramba
  • 21,963
  • 19
  • 86
  • 127
  • I'd start by looking in your browsers developer tools outbound requests to validate the ajax library you're using is indeed sending the X-Requested-With header – Daniel Mar 04 '19 at 21:34
  • Also, the documentation for XMLHttpRequest is a good start. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest – Roman Mik Mar 04 '19 at 21:36
  • @Daniel Type says "xhr" https://imgur.com/a/m8OUFq7 – caramba Mar 04 '19 at 21:39
  • @RomanMik that's exactly where I've got the snippet from. The problem is not the browser! I wonder how I can react on it on the server side – caramba Mar 04 '19 at 21:40
  • What's is the error with `new HttpRequestWrapper(System.Web.HttpContext.Current.Request).IsAjaxRequest()` ? – The One Mar 04 '19 at 21:42
  • @caramba expand the request and see what is being sent by the browser to your server, you will see the list of headers (if any) – Roman Mik Mar 04 '19 at 21:43
  • @RomanMik it's a huge list see here: https://imgur.com/a/wRWFuiQ didn't find any matching xmlHttpRequest – caramba Mar 04 '19 at 21:46
  • @TheOne it's tells me `HttpRequestWrapper does not exist in current namespace` – caramba Mar 04 '19 at 21:47
  • please follow the link below https://stackoverflow.com/questions/29282190/where-is-request-isajaxrequest-in-asp-net-core-mvc – Muhammad Ali Mar 04 '19 at 22:36
  • @MuhammadAli thank you for the link but I don't see how I can add that functionality. Any more hints? – caramba Mar 04 '19 at 22:44

3 Answers3

2

You can do the following:

    // GET: Movies/Create
    public IActionResult Create()
    {
        string requestedWith = HttpContext.Current.Request.Headers["X-Requested-With"];

        if(requestedWith == "XMLHttpRequest")
        {
           // Do whatever you want when an AJAX request comes in here....
        }

        return View();
    }

Be aware that, in reality, there is no foolproof way to detect AJAX requests -- the X-Requested-With header is optionally sent by the developer or a client library, such as jQuery. So there is no guarantee this header will be sent, unless of course, you are the developer of the only client side code that will use this service. To the server, there is nothing that differentiates an AJAX request from any other kind of request.

Byron Jones
  • 702
  • 5
  • 11
  • Hi, thank you for this answer. I didn't have time to get back to this earlier. If I try this I get: "HttpContext" does not contain a definition for "Current" – caramba Mar 05 '19 at 18:34
  • @caramba Make sure you're using `System.Web`, and use `System.Web.HttpContext.Current.Request.Headers["X-Requested-With"]` – Byron Jones Mar 05 '19 at 20:03
  • why `"X-Requested-With"` and not `XMLHttpRequest` like in my answer? – caramba Mar 05 '19 at 20:06
  • 1
    @caramba Really you can name the header whatever you like, `X-Requested-With` is simply the standard name for a header describing the client that made request. If you like `XMLHttpRequest`, go for it. The important part of my comment is to make sure you prepend `HttpContext` with `System.Web` as shown. – Byron Jones Mar 05 '19 at 20:25
2

As Byron Jones pointed out in the answer I needed to set the the MLHttpRequest.setRequestHeader() my self and if you follow the link you will see it's as simple as adding

oReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

so updated my code from the question like so:

// C# needs the line:
public IActionResult Create()
    {
        ViewData["xmlHttpRequest"] = false;
        if (HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
            ViewData["xmlHttpRequest"] = true;
        }

        return View();
    }


// and javascript like so:
function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://localhost:5001/Movies/Create");
oReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // this is the only new line
oReq.send();

From the documentation it's stated

The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header. When using setRequestHeader(), you must call it after calling open(), but before calling send(). If this method is called several times with the same header, the values are merged into one single request header.

Follow the links for more information.

caramba
  • 21,963
  • 19
  • 86
  • 127
0

You didn't import extension AjaxRequestExtensions. This is why you get an error on the first line

Request.IsAjaxRequest(); // this line tells me "HttpRequest does not contain a defintion for IsAjaxRequest .. (are you missing a using directive?)"

Alin
  • 592
  • 1
  • 7
  • 21
  • how can I import the `AjaxRequestExtensions` ? – caramba Mar 04 '19 at 21:55
  • Sorry, you don't have to import it, should be already in System.Web.Mvc. What version of MVC are you using. I just tested with MVC 5 and it is there. – Alin Mar 04 '19 at 22:10
  • All I can find says "framework": { "name": "Microsoft.AspNetCore.App", "version": "2.2.0" } I've been following [this example](https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.2), so it should be kind of new but can not find any MVC related version – caramba Mar 04 '19 at 22:28
  • For ASP.NET Core application see this post https://stackoverflow.com/questions/29282190/where-is-request-isajaxrequest-in-asp-net-core-mvc – Alin Mar 05 '19 at 07:39
  • Thanks for trying to help, same link has been metioned already 10h ago a few lines further up on this question [see comment here](https://stackoverflow.com/questions/54991671/c-sharp-mvc-detect-if-xmlhttprequest?noredirect=1#comment96742596_54991671) – caramba Mar 05 '19 at 07:43