Home > Mobile >  Is there any way to get data type of XMLHttpRequest on base controller in .net core 3.1
Is there any way to get data type of XMLHttpRequest on base controller in .net core 3.1

Time:11-02

Here is any Jquery ajax POST request;

$.ajax({
    type: "POST",
    url: "/Customers/GetAll",
    contentType: "application/json",
    dataType: "json",
    success: function(response) {
        console.log(response);
    },
    error: function(response) {
        console.log(response);
    }
});

Here is my Controller Action Method which requested by ajax above;

public IActionResult GetAll()
{
    //Method body...
}

How can I get the dataType of any ajax request in base controller or action method?

CodePudding user response:

Try to get accept in headers:

enter image description here

action:

 public IActionResult GetAll()
        {
            string dataType = HttpContext.Request.Headers["accept"].ToString();
            //Method body...
        }

CodePudding user response:

The headers can be retrieved on the HttpContext object.

if(HttpContext.Request.Headers.TryGetValue("accept", out var acceptHeaders)) {
   var firstAcceptHeader = acceptHeaders.FirstOrDefault();
}

You can also access the header value using indexing Headers["accept"], but be aware, that if there is no accept header, for whatever reason, this will throw a NullReferenceException.

  • Related