I have an application done in .netframework 2.0 and trying to use an authentication handler in a security project, which is written in 3.5 framework. Also I m using IIS 7
Web.config of the application has the following entry
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<handlers accessPolicy="Read, Write, Script, Execute">
<add name="Pdfhandler" verb="*" path="/calderdale/*.pdf" type="NES.HiLo.Security.CalderDaleAuthenticationHandler, NES.HiLo.Security" preCondition="integratedMode" />
</handlers>
</system.webServer>
The code for CalderDaleAuthenticationHandler is
using System;
using System.Web;
namespace NES.HiLo.Security
{
public class CalderDaleAuthenticationHandler : IHttpHandler
{
/// <summary>
/// You will need to configure this handler in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
/// </summary>
#region IHttpHandler Members
public bool IsReusable
{
// Return false in case your Managed Handler cannot be reused for another request.
// Usually this would be false in case you have some state information preserved per request.
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//var application = (HttpApplication)sender;
//var context = application.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
// Check if the user is authenticated
}
#endregion
}
}
In my application I have a folder name calderdale and I have some pdf files. when I type in some thing like below to access the pdf file. I am expecting the control to go to handler, where I have set breakpoints. The control never goes to the handler. I appreciate any help.
http://local.knowledge.scot.nsh.uk/calderdale/abc.pdf
I used httphandlers to intercept the request. Then added a handler like this in web.config
<httpHandlers>
<add verb="GET" path="calderdale/*.pdf"
type="NES.HiLo.Security.CalderDaleAuthenticationHandler, NES.HiLo.Security" />
</httpHandlers>
After the above on IIS 7.0 I added the following handler from IIS Handlers section
<system.webServer>
<handlers>
<add name="Calderdale Handler" path="calderdale/*.pdf"
verb="GET" modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
resourceType="Unspecified" requireAccess="Script"
preCondition="classicMode,runtimeVersionv2.0,bitness32" />
</handlers>
</system.webServer>
Related
I want to enable CORS on one specific action in an Asp.net Web Api. Here's how I'm trying to do it:
[Route("api/mycontroller/myaction")]
[HttpPost]
[EnableCors("https://example.com", "*", "post")]
public async Task<IHttpActionResult> MyAction()
{
...
}
But when I send an OPTIONS request to the route, I get back an error: "The requested resource does not support http method 'OPTIONS'." I also tried removing the [HttpPost] annotation to no avail.
What am I missing?
For me, I added the following headers to the request by adding the following code to the Application_BeginRequest function of the Global.asax.cs file:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.CurrentCultureIgnoreCase)
&& Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Headers", "content-type", "accept", "pragma", "cache-control", "authorization");
Response.End();
}
}
I have little idea why this works.
Out of curiosity, I tried adding all headers by using an asterisk but then Web API complained that the Authorization header was missing.
You've probably missed the higher level call to HttpConfiguration.EnableCors, as described here: https://enable-cors.org/server_aspnet.html.
Add this code to your configuration:
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
}
To ensure the OPTIONS request gets handled by your application code and not some other part of the system before it reaches your app code, you may try adding the following to your web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
You might also need to include:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="IsapiModule" requireAccess="None"
scriptProcessor="C:\Windows\System32\inetsrv\asp.dll"
resourceType="Unspecified" />
See the answer at IIS hijacks CORS Preflight OPTIONS request.
Or maybe even just this:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="ProtocolSupportModule" requireAccess="None" />
If none of that on its own works, then in your global.asax or other code you might try:
if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
filterContext.HttpContext.Response.Flush();
}
…or some other variation on that, for example:
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase)
&& Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
Regardless of what specific code you use to do it, the point is to:
make sure OPTIONS requests are actually getting caught/handled by your application code—not caught/handled by some other part of the system before ever reaching your app code
make sure you have explicit handling for OPTIONS requests in your application code
make the OPTIONS handling in your application code just do Response.Flush()
Or another approach I’m not sure is relevant to your situation as coded but I’ll mention just in case:
public HttpResponseMessage Options()
{
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK
};
return response;
}
I am writing a handler to process a resource and I am facing an issue, when the implemented IHttpHandler Class is written under a namespace.
Please find the code
Not working scenario
Web.config:
<add name="ResourceHandler" type="PublicSite.Classes.Handlers.ResourceEndpoint, PublicSite" path="Resource.ashx" verb="*" />
Property: PublicSite.Classes.Handlers.ResourceEndpoint.IsReusable=False
Issue: Constructor is hit and the ProcessRequest is not invoked. Constructs the object of the class, ie., Constructor is hit , however fails by 404 before the processrequest is invoked.
Working Scenario
Web.config:
<add name="ResourceHandler" type="ResourceEndpoint,PublicSite" path="Resource.ashx" verb="*" />
Class: PublicSite.Classes.Handlers.ResourceEndpoint.IsReusable=True
Constructor is hit and fails by 404 before the processrequest is invoked.
Second time when we request for the handler, it straight away uses the constructed object so construcotr is not invoked and the ProcessRequest is invoked directly. By the way in the second call the handler is working.
I dont require the reusable property.
Can some one help me to find the issue. Thanks.
Can you confirm to me that your web.config and handler itself looks like the following ? (This is from a project hosted under IIS 7.5)
web.config: -
<system.webServer>
<handlers>
<add name="customerHandler"
preCondition="integratedMode"
verb="*"
path="customerHandler.ashx"
type="GlassCMS.HttpHandlers.CustomerHandler, GlassCMS"/>
.
.
.
</handlers>
</system.webServer>
HttpHandler: -
[WebService(Namespace = "http://{redacted.com}/json-http-handlers/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CustomerHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string json = string.Empty;
// code to do whatever here...
context.Response.Write(json);
}
I can include the JavaScript as well if you want (or you can post yours here). This example above is from working code.
I'm having a strange and weird situtation here.
If I send a request to: /scenes/?lang=es-ar, the headers are set just fine and everything seems OK.
However, if I send one to: /scenes/?lang=es-ar&sort.asc=creation, the headers are missing and I'm unable to fetch the response due to cross origin.
CORS is automatically managed by Owin's CORS Middleware, so this is out of my hands.
Here is my middleware's configuration:
private void ConfigureCors(IAppBuilder application)
{
CorsPolicy policy = new CorsPolicy()
{
AllowAnyHeader = true,
AllowAnyOrigin = true,
SupportsCredentials = true,
};
policy.Methods.Add("GET");
policy.Methods.Add("POST");
policy.Methods.Add("PUT");
policy.Methods.Add("DELETE");
policy.Methods.Add("OPTIONS");
policy.ExposedHeaders.Add("Location");
application.UseCors(new CorsOptions()
{
PolicyProvider = new CorsPolicyProvider()
{
PolicyResolver = request => System.Threading.Tasks.Task.FromResult(policy)
}
});
}
Why are the headers not being sent on the response?
I'm guessing it has something to with the "." (dot) in sort.asc=creation
I'm using latest version of ASP.NET Web Api (5.2.3) and Microsoft.Owin.Cors (3.0.1)
There might be a possibility that hosting server IIS might be intercepting the pre-flight requests. To ensure ASP.NET handles OPTION requests, add the following in web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
In my opinion this is not a decent choice to use Microsoft.Owin.Cors with WebAPI, if you're planning to use IIS as hosting environment. A better choice for Asp.net WebAPi would be Asp.net web API implementation of CORS.
I have a very simple NancyFX module which I simply want to echo the results of an API call back to the sender.
I am using a facade which converts incoming XML to JSON before handing it off to the Nancy endpoint. This facade changes the content to JSON correctly as I can test it using the echo service for the api and can see the response.
However, because the facade removes the content-length header and sets transfer-encoding to chunked, the Request.Body is always empty in my Nancy module.
Is there a configuration needed to enable support for Chunked encoding in NancyFX?
I am hosting on IIS 7 currently, but have access to IIS 8 as well.
I can see that using OWIN hosting it is possible to enable chunked transfer using HostConfiguration, but due to other factors I cannot use OWIN hosting and rely on IIS hosting.
I have enabled chunked transfer on IIS with the command:
appcmd set config /section:asp /enableChunkedEncoding:True
My web.config is currently:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpHandlers>
<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</httpHandlers>
<httpRuntime targetFramework="4.5.1" />
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
<system.webServer>
<modules>
<remove name="WebDavModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
The module itself is very simple and consists of:
Post["/"] = parameters =>
{
var traceRef = Guid.NewGuid();
var body = this.Request.Body.AsString();
Logger.Trace("Trace ref: {0}, request inbound.", traceRef);
Logger.Trace(body);
AuthRequest auth = new AuthRequest();
try
{
auth = this.Bind<AuthRequest>();
}
catch (Exception ex)
{
Logger.Error("Trace ref: {0}, error: {1}. Exception: {2}", traceRef, ex.Message, ex);
}
var responseObject = new
{
this.Request.Headers,
this.Request.Query,
this.Request.Form,
this.Request.Method,
this.Request.Url,
this.Request.Path,
auth
};
return Response.AsJson(responseObject);
};
My first thought when reading this was Transfer-Encoding is only meant for responses not requests. Looking at the list of HTTP header fields, Transfer-Encoding is only listed under Response Fields. But the spec doesn't mention request or response just sender and recipient. Now I'm not so sure.
Anyway, the ASP.NET hosting code explicitly excludes the body if the content length is 0, but the self-hosting code doesn't seem to have the same restriction. I'm not sure if this difference is intentional. You could remove the if statement that checks the content length and send a PR to the Nancy team. See what they come back with.
I have ASP.NET handler. But when I try to call it it says :
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
namespace SimpleHTTPHanlder
{
public class SimpleHandler : IHttpHandler
{
#region IHttpHandler Members
bool IHttpHandler.IsReusable
{
get { return true; }
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
response.Write("<html><body><h1>Wow.. We created our first handler");
response.Write("</h1></body></html>");
}
#endregion
}
}
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="*" path="vishal.nayan" type="SimpleHTTPHanlder.SimpleHandler"/>
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
I try to make request like this, but with unsuccess:
http://localhost:60223/SimpleHTTPHanlder/vishal.nayan
Looking at our code which works, some ideas:
Try adding the handler under system.webServer instead of system.web
Try adding the attribute preCondition="integratedMode"
Try specifying a name attribute
I think as you have written your path as
http://localhost:60223/SimpleHTTPHanlder/vishal.nayan.
Instead of this try
http://localhost:60223/vishal.nayan
This is because your path element contain vishal.nayan only.
<httpHandlers>
<add verb="*" path="vishal.nayan" type="SimpleHTTPHanlder.SimpleHandler"/>
</httpHandlers>
if you still have issue then tell me does you have hosted on IIS or IIS express ?
If you have configured in IIS ( IIS 7 or 7.5 later then you have to configure in
<system.webServer>
<handlers>
<add name="test" verb="*" path="vishal.nayan" type="SimpleHTTPHanlder.SimpleHandler"/>
</handlers>
...... other configuration
</system.webServer>
http://localhost:60223/SimpleHTTPHanlder/vishal.nayan
is it a copy/paste with a typo ? ( Hanlder )