C. Tewalt
C. Tewalt

Reputation: 2509

How does ASP.NET know whether a request is AJAX or not?

I'm writing an MVC application and I was stunned to know that I could do a Request.isAJAXRequest() in my controller and return a JSONResult if it was AJAX, or return a regular HTML Razor View if it wasn't.

This is incredibly useful, but I'm wondering how this actually works underneath. Is there something in the header that designates it as AJAX?

Here is the request header of an AJAX POST that I pulled from IE Developer tools. enter image description here

Upvotes: 3

Views: 190

Answers (2)

mohsen dorparasti
mohsen dorparasti

Reputation: 8415

it's X-Requested-With header in the request headers.

and because the header can be removed or changed it's not a complete, guaranteed solution to detect ajax calls.

update:

in your situation ( return proper format to client ), another way could be to check Accept header. it could be json , xml , html or other things. based on that you can decide what to return back.

Upvotes: 2

Björn
Björn

Reputation: 29381

Yes, the header called X-Requested-With tells the server that XMLHttpRequest was used to make the request (i.e. Ajax).

Upvotes: 6

Related Questions