Where is Request.IsAjaxRequest() in Asp.Net Core MVC?
in asp.net core, You can use Context.Request.Headers.
bool isAjaxCall = Context.Request.Headers["x-requested-with"]=="XMLHttpRequest";
I got a little confused, because the title mentioned MVC 5.
Search for Ajax
in the MVC6 github repo doesn't give any relevant results, but you can add the extension yourself. Decompilation from MVC5 project gives pretty straightforward piece of code:
/// <summary>
/// Determines whether the specified HTTP request is an AJAX request.
/// </summary>
///
/// <returns>
/// true if the specified HTTP request is an AJAX request; otherwise, false.
/// </returns>
/// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
public static bool IsAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (request["X-Requested-With"] == "XMLHttpRequest")
return true;
if (request.Headers != null)
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
return false;
}
Since MVC6 Controller
seems to be using Microsoft.AspNet.Http.HttpRequest, you'd have to check request.Headers
collection for appropriate header by introducing few adjustments to MVC5 version:
/// <summary>
/// Determines whether the specified HTTP request is an AJAX request.
/// </summary>
///
/// <returns>
/// true if the specified HTTP request is an AJAX request; otherwise, false.
/// </returns>
/// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
if (request.Headers != null)
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
return false;
}
or directly:
var isAjax = request.Headers["X-Requested-With"] == "XMLHttpRequest"
For those who are working on ASP.Net Core
HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
Example
Controller.cs
bool isAjax = HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (isAjax)
return Json(new { redirectTo = Url.Action("Index", "ControllerAction") });
else
return RedirectToAction("Index", "ControllerAction");