Impossible to show Custom Error page with Nancy on OWIN - owin

I have a website using Nancy which is hosted using OWIN.
In my Startup.cs file I define the PassThroughOptions as follows:
public void Configuration(IAppBuilder app)
{
app.UseNancy(o => {
o.PassThroughWhenStatusCodesAre(
HttpStatusCode.NotFound,
HttpStatusCode.InternalServerError
);
o.Bootstrapper = new Bootstrapper();
});
app.UseStageMarker(PipelineStage.MapHandler);
}
I need to pass-through the NotFound requests, so that things like my bundled .less files or miniprofiler-results or static files in the root of my site (robots.txt or sitemap.xml) work.
I also have a custom StatusCodeHandler for the 404 code, which also checks a custom header to distinguish between static files (or .less bundles/miniprofiler) and actual stuff that is not found in my modules' methods.
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
Log.Warn("Not found: " + context.Request.Url);
base.Handle(statusCode, context, "Errors/NotFound");
}
This handler then should actually show the error page.
protected void Handle(HttpStatusCode statusCode, NancyContext context, string view)
{
var response = new Negotiator(context)
.WithModel(GetErrorModel(context))
.WithStatusCode(statusCode)
.WithView(view);
context.Response = responseNegotiator.NegotiateResponse(response, context);
}
But the error page is never shown. The request is processed three times and eventually the default IIS error page is shown (using errorMode="Custom" for httpErrors) or simply a white page (using existingResponse="PassThrough" for httpErrors).
Is there any way to display something so simple as a custom error page when hosting a Nancy website on OWIN?

What you've got there looks good, it looks like you've be using the Hosting Nancy with Owin docs.
Here's what works for me:
The Startup.cs (required for Owin): (We've both coded the configuration function differently, you're just using the extension helper while I'm not. Same result. This is in my App.Web project.)
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy(options =>
{
options.Bootstrapper = new BootStrapper();
options.PerformPassThrough = context => context.Response.StatusCode == HttpStatusCode.NotFound;
});
app.UseStageMarker(PipelineStage.MapHandler);
}
}
404 handler: (As per the docs, doesn't matter where this is in the project, by implementing IStatusCodeHandler it'll be automatically picked up by Nancy This is in my App.WebApi project with other module classes.)
public class StatusCode404Handler : IStatusCodeHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
return statusCode == HttpStatusCode.NotFound;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
var response = new GenericFileResponse("statuspages/404.html", "text/html")
{
StatusCode = statusCode
};
context.Response = response;
}
}
The 'statuspages' folder in my App.Web project:
Check this SO post for a comparison of using GenericFileReponse or ViewRenderer (How to display my 404 page in Nancy?).

Related

How to insert code in the static files like .html, .htm, .asp on IIS for non-asp project

I want to add a script on my IIS Server.
So that it will be applied on all the websites that are upload will have that script in their request response.
Anyone who knows how to do it?
I had implemented the IHttpModule and IHttpHandler, it works fine for the asp.net projects.
but if the website contains only html, css, and js files in the folder, this solution doesn't work.
Here the HttpModule and HttpHandler
public class MyCustomHttpModuleClass : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
}
public void OnPostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
context.Response.Write("<h1>alert('HELLO')</h1>");
}
}
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<h1>alert('HELLO')</h1>");
}
}
I'm not sure if you have learnt how to add Custom Module and Handler in IIS. After tested your module and handler with static website, it works fine.
I will just give you a sample of adding them to IIS.
1.Create a project "class library .netframework". I name the project"ClassLibrary1"
2.Add class "MyCustomHttpModuleClass" and "MyHandler" to the project
3.Build this solution and find "ClassLibrary1.dll" in the "project/bin/debug" folder.
4.Copy "ClassLibrary1.dll" to the website root "BIN" folder.
5.Add managed module and handler by choose your dll.(should in the list after you copied)Just mention that your custom handler only work on the file extension you set up.
Now they work.

How to customize default error pages in azure web app for linux?

I have hosted .NET core 3.1.1 LTS app in Azure web app for linux? How do I customize default error pages like
1. 502
2 Error pages when app service is stopped.
3 Error page when app is being published from Visual studio , VS code / FTP
I find a docs about creating Application Gateway custom error pages,maybe it's good for you. custom error pages
How to create custom error page in code.
We also can handle it by code.Here is my suggest.
Errors like 500, we can handle it by filter,
public class ErrorPageFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{
if (context.HttpContext.Response.StatusCode == 500)
{
context.HttpContext.Response.Redirect("error/500");
}
base.OnResultExecuted(context);
}
}
[ErrorPageFilter]
public abstract class PageController
{}
For .netcore mvc project, it also comes with pipeline processing for error pages when it is created.
In startup.cs,
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//dev env show error page
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//prod env show custom page
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
}
//In HomeController has this function,
//You just replace cshtml file by you want
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
Errors like 404, we can,
In startup.cs file find configure function,then add below code,
app.UseStatusCodePagesWithReExecute("/error/{0}");
Then add error Controller,
public class ErrorController : Controller
{
/// <summary>
/// In content in {0} is error code
/// </summary>
/// <returns></returns>
[Route("/error/{0}")]
public IActionResult Page()
{
//Jump to 404 error page
if (Response.StatusCode == 404)
{
return View("/views/error/notfound.cshtml");
}
return View();
}
}
Pay attention, if use ErroeController( handle 404 error), pls don't use
app.UseExceptionHandler("/Home/Error"),
you just need handle error in Controller.

SwaggerRequestExample attribute does not work in ASP.NET MVC 5 (.NET Framework 4.5.2)

I am toying with Swashbuckle.Examples package (3.10.0) in an ASP.NET MVC project. However, I cannot make request examples appear within the UI.
Configuration (SwaggerConfig.cs)
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c => {
c.SingleApiVersion("v1", "TestApp.Web");
c.IncludeXmlComments(string.Format(#"{0}\bin\TestApp.Web.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.OperationFilter<ExamplesOperationFilter>();
c.OperationFilter<DescriptionOperationFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
})
.EnableSwaggerUi(c => { });
}
Request example classes
public class EchoRequestExample : IExamplesProvider
{
public object GetExamples()
{
return new EchoInput { Value = 7 } ;
}
}
public class EchoInput
{
public int Value { get; set; }
}
Action
[HttpGet]
[Route("Echo")]
[CustomApiAuthorize]
[SwaggerRequestExample(typeof(EchoInput), typeof(EchoRequestExample))]
[ResponseType(typeof(EchoServiceModel))]
public HttpResponseMessage Echo([FromUri] EchoInput model)
{
var ret = new EchoServiceModel
{
Username = RequestContext.Principal.Identity.Name,
Value = value
};
return Request.CreateResponse(HttpStatusCode.OK, ret);
}
Swagger UI shows xml comments and output metadata (model and an example containing default values), but shows no request example. I attached to process and EchoRequestExample.GetExamples is not hit.
Question: How to make SwaggerRequestExample attribute work in ASP.NET MVC 5?
Note: Windows identity is used for authorization.
I received an answer from library owner here:
Swagger request examples can only set on [HttpPost] actions
It is not clear if this is a design choice or just a limitation, as I find [HttpGet] examples also relevant.
I know the feeling, lot's of overhead just for an example, I struggle with this for a while, so I created my own fork of swashbuckle, and after unsuccessful attempts to merge my ideas I ended up detaching and renaming my project and pushed to nuget, here it is: Swagger-Net
An example like that will be:
[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{
Here the full code for that: Swagger_Test/Controllers/IHttpActionResultController.cs#L26
Wondering how that looks like on the Swagger-UI, here it is:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=IHttpActionResult#/IHttpActionResult/IHttpActionResult_GetById

Redirect ends up outside of application

I am working on a .Net Core web application and we would like to be able to redirect a type of url to our custom error page. The site is hosted on Azure and it seems that this error is not being handled in the application. Here is the type of URL I am working with:
www.mywebsite.com/%22http://www.yahoo.com/%22
The error page that is presented is the following:
The page cannot be displayed because an internal server error has occurred.
In addition when I check the live HTTP traffic on Azure it does not show an error occurring.
Edit:
Apparently azure cannot handle this type request at all: https://azure.microsoft.com/%22/http://www.google.com/
It looks for the config file within the second url. Does anyone know where I can file a bug with Microsoft?
I haven't tested this on Azure, however it works on our server.
Configure exceptions handling in Startup class.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ...
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
}
// ...
app.UseStatusCodePagesWithRedirects("/error/{0}");
// ...
}
And error controller.
[Route("[controller]")]
public class ErrorController : Controller
{
[Route("")]
public IActionResult Index()
{
return View();
}
[Route("{httpStatusCode}")]
public IActionResult Index(int httpStatusCode)
{
// handle by error code
switch (httpStatusCode)
{
case (int)HttpStatusCode.NotFound:
return View("NotFound");
default:
return View();
}
}
}

Owin hosted web app using Token authentication

I am trying to create an owin web app using token authentication, my startup does not have any special setup like the example in
https://github.com/NancyFx/Nancy/wiki/Token-Authentication
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve<ITokenizer>()));
}
}
mine is simply
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
I have the module defined like
public HomeModule(ITokenizer tokenizer)
{
Post["/login"] = _ =>
{
DefaultUserIdentityResolver resolver = new DefaultUserIdentityResolver();
//var userName = (string)this.Request.Form.Username;
//var password = (string)this.Request.Form.Password;
var claims = new List<string> { "admin", "poweruser" };
var userIdentity = resolver.GetUser("ross", claims, Context);
if (userIdentity == null)
{
return HttpStatusCode.Unauthorized;
}
var token = tokenizer.Tokenize(userIdentity, Context);
return new
{
Token = token,
};
};
}
Not much just yet I know but when when I get to tokenize I get an exception of the type Nancy.ErrorHandling.RouteExecutionEarlyExitException which really doesnt have anything in the message or stack trace to indicate the issue.
I am currently hosting over http in casini on .NET 4.5.1
Any pointers would be appreciated
Update:
Message is:
Exception of type 'Nancy.ErrorHandling.RouteExecutionEarlyExitException' was thrown.
Stack trace is:
at Nancy.Authentication.Token.Tokenizer.Tokenize(IUserIdentity userIdentity, NancyContext context)
at Samaritan.Hosting.HttpServices.HomeModule.<>c__DisplayClass11.<.ctor>b__7(Object _) in c:\src\DukeSoftware\Samaritan\Main\Samaritan.Hosting.HttpServices\HomeModule.cs:line 39
at CallSite.Target(Closure , CallSite , Func`2 , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at Nancy.Routing.Route.<>c__DisplayClass4.<Wrap>b__3(Object parameters, CancellationToken context)
I tried setting up the startup.cs like this
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
}
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve<ITokenizer>()));
}
}
but I got the following exception
{"Located multiple bootstrappers:\r\n - Samaritan.Hosting.HttpServices.BootStarapper\r\n - Samaritan.Hosting.HttpServices.Bootstrapper\r\n\r\nEither remove unused bootstrapper types or specify which type to use."}
So I removed the bootsrapper and just left Startup. An instantiated tokenizer seems to be passed into the module when you declare the constructor public HomeModule(ITokenizer tokenizer)
So I didnt think the creation of the tokenizer was a problem
did you find fix?
I'm encountering the same exception. It's because I have 2 EXE files in the same directory having child of 'DefaultNancyBootstrapper' class.
I gotta use old Nancy v1.0. so it seems there's no other way but to use 'DefaultNancyBootstrapper' in only one place.

Resources