I can’t find an asp.net core c# function or code example to test if an HTTP reponse is programmatic.
In asp.net (core) 8.0 c#, I am determining if a web response is html or javascript with
if ( context.HttpContext.Response.StatusCode < 400 &&
(
context.HttpContext.Response.ContentType.Contains("text/javascript") ||
context.HttpContext.Response.ContentType.Contains("application/javascript") ||
context.HttpContext.Response.ContentType.Contains("text/html") ||
context.HttpContext.Response.ContentType.Contains("text/xml")
))
{
// Proceed with operations on replies that might be programmatic
}
This does work on the websites I try (an admittedly very poor sample of less than a dozen websites).
I should note that I’m not doing security related code, so I am OK trusting the ContentType. I’m not trying to determine if someone is maliciously altering the headers.
The most obvious problem is I would think I am missing relatively common client side applications (I’m only testing for (x)html and javascript). Browsers and extensions might run python? jquery might not use application/javascript MIME type sometimes? I don’t know. (I’m not testing for java code, but am uncertain if that is an issue, without a java plugin).
Also, the above code seems pretty inefficient (faster try is below). Is there some function or library out there that will do this quicker? I searched in stackoverflow and generally googled but my searches aren’t finding anything.
More efficient code, but less accuracy could be a problem:
string mimePrefix,mimeSuffix, mimeScript;
if (null != context.HttpContext.Response.ContentType &&
context.HttpContext.Response.ContentType.Length >= 8)
{
mimePrefix = context.HttpContext.Response.ContentType.Substring(0, 5); // "text/"
mimeSuffix = context.HttpContext.Response.ContentType.Substring(5, 3); // First three chars after "text/", so this would be "htm" for "text/html"
if (context.HttpContext.Response.ContentType.Length < 22)
mimeScript = "";
else // find "application/javascript" if present
mimeScript = context.HttpContext.Response.ContentType.Substring(0, 22);
}
else
{
mimePrefix = mimeSuffix = mimeScript = "";
}
if ( context.HttpContext.Response.StatusCode < 400 &&
(
"text/" == mimePrefix &&
("jav" == mimeSuffix || "htm" == mimeSuffix ||
"xml" == mimeSuffix)
)
|| "application/javascript" == mimeScript
)
{
// Proceed with operations on replies that might be programmatic
}
Again, just wondering if there is some function or library I should be using, or if there is a better coding algorithm that be more accurate or faster, or better in other ways.