I have a unique situation where I need to get the DepartmentId from either the [FromRoute] or [FromQuery] or [FromBody]. This is weird as I cannot break my public api action contracts and cannot do much about it. Also I cannot alter the business contracts which is called inside from the controller, so that I cannot pass the DepartmentId down the pipeline.
I see that I can inject the IHttpContextAccessor and get the IHttpContextAccessor.HttpContext. I was able to get the DepartmentId for [FromQuery] as below:
request.QueryString.Value.Replace("?", "")
.Split("&")
.FirstOrDefault(x => x.Contains("departmentId"))
?.Split("=")[1];
I am getting it [FromRoute] parameter as below;
var departmentId = 0;
var match = Regex.Match(request.Path, "Department/\\d+");
if (match.Success && match.Groups.Any())
{
int.TryParse(match.Groups[0].Value.Replace("Department/", ""), out departmentId);
}
I do not know how I can get the DepartmentId from the [FromBody] complex object. But I do know that all the request objects used in the [HttpPost] is inheriting from the Department class which has a DepartmentId.
Any helps are appreciated....
Request.InputStreamcontains the body of the HTTP request; accessible as aStreamInputStreaminsideRequest. I am using .net core if you have not noticed that. Did you meanIHttpContextAccessor.HttpContext.Request?