How to display my 404 page in Nancy? - asp.net

I need to display my 404 error page in Nancy like this
if (ErrorCode == 404)
{
return View["404.html"];
}
How to do it?

The answer from nemesv is correct, but I just wanted to add an example using the ViewRenderer instead of the GenericFileResponse.
public class MyStatusHandler : IStatusCodeHandler
{
private IViewRenderer viewRenderer;
public MyStatusHandler(IViewRenderer viewRenderer)
{
this.viewRenderer = viewRenderer;
}
public bool HandlesStatusCode(HttpStatusCode statusCode,
NancyContext context)
{
return statusCode == HttpStatusCode.NotFound;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
var response = viewRenderer.RenderView(context, "/status/404");
response.StatusCode = statusCode;
context.Response = response;
}
}

You just need to provide an implementation of the IStatusCodeHandler interface (it will be picked up automatically by Nancy).
In the HandlesStatusCode method return true for the HttpStatusCode.NotFound.
And in the Handle method you need to set the Response property on the NancyContext with a response containing your error page content. You can use for example the GenericFileResponse:
public class My404Hander : IStatusCodeHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode,
NancyContext context)
{
return statusCode == HttpStatusCode.NotFound;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
var response = new GenericFileResponse("404.html", "text/html");
response.StatusCode = statusCode;
context.Response = response;
}
}

Related

How to create a custom error message for Authorize attribute?

I want only admins to have access to this controller and its actions, so I've written this code:
[Authorize(Roles = Helper.AdminRole)]
public class AdminController : Controller
{
public IActionResult AdminPanel()
{
return View();
}
//other actions only available to admins
}
If the user is not logged in and he's not in the specified role I get a 404 Not Found page and this in the URL:
..../AccessDenied?ReturnUrl=%2FAdmin%2FAdminPanel
How can I make a custom error page for this scenario where the user is asked to log in so he can confirm his role, and when he does log in successfully AND he is in the right role to be redirected to where he wanted to go, but if his role is invalid to be redirected elsewhere/ shown a custom error page?
Your error was caused due to lack of Loginpath settings,not wrong role or password.(So the error code was 404 not 401)
You could see the test Result:
If you want to custom error page,you could read the official document:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-5.0
I tried with the codes below:
ErrorResult class:
public class ErrorResult
{
public bool Success { get; set; } = true;
public string Msg { get; set; } = "";
public string Type { get; set; } = "";
public object Data { get; set; } = "";
public object DataExt { get; set; } = "";
}
ErrorHandlingMiddleware:
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
var statusCode = context.Response.StatusCode;
if (ex is ArgumentException)
{
statusCode = 200;
}
await HandleExceptionAsync(context, statusCode, ex.Message);
}
finally
{
var statusCode = context.Response.StatusCode;
var msg = "";
if (statusCode == 401)
{
msg = "unauthorize";
}
else if (statusCode == 404)
{
msg = "NotFound";
}
else if (statusCode == 400)
{
msg = "BadRequest";
}
else if (statusCode != 200)
{
msg = "Unkonwn";
}
if (!string.IsNullOrWhiteSpace(msg))
{
await HandleExceptionAsync(context, statusCode, msg);
}
}
}
private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
{
var result = JsonConvert.SerializeObject(new ErrorResult() { Success = false, Msg = msg, Type = statusCode.ToString() });
context.Response.ContentType = "application/json;charset=utf-8";
return context.Response.WriteAsync(result);
}
}
public static class ErrorHandlingExtensions
{
public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandlingMiddleware>();
}
}
in startup class:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
app.UseErrorHandling();
....
}
The Result:
Take cookie authentication as an example, you just need to configure it like this in program.cs(.Net 6):
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
//When user doesn't login and he access to an action with [Authorize],
//He will redirect to the loginPath
x.LoginPath = "/{controller}/{action}";
//When user has loged in but the role is not the specified role,
//He will redicet to the AccessDeniedPath,
//Then you can custom your own error page in this path.
x.AccessDeniedPath = "/{controller}/{action}";
});

HttpContext.Current is null when using IAuthenticationFilter

I am uploading files using ng-file-upload and having some abnormal problem as the HttpContext.Current is null when using the IAuthenticationFilter. While everything working correctly when I comment the authentication filter in WebApiConfig.
Controller to Test
[HttpPost]
public IHttpActionResult Upload()
{
var current = HttpContext.Current;
if (current == null)
{
return Content(HttpStatusCode.BadRequest, Logger.Error("HttpContext.Current is null"));
}
if (current.Request != null && current.Request.Files != null)
{
var file = current.Request.Files.Count > 0 ? current.Request.Files[0] : null;
if (file != null)
{
file.SaveAs(#"C:\Temp\test.csv");
}
}
return Content(HttpStatusCode.BadRequest, Logger.Error("Should not reach here"));
}
IAuthenticationFilter
public class KeyAuthentication : Attribute, IAuthenticationFilter
{
// we only want to apply our authentication filter once on a controller or action method so return false:
public bool AllowMultiple
{
get { return false; }
}
// Authenticate the user by apiKey
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
HttpRequestMessage request = context.Request;
string apiKey = ExtractApiKey(request);
bool IsValidCustomer = await ValidateKey(apiKey);
if (IsValidCustomer)
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(apiKey), null);
context.Principal = principal;
}
else
{
context.ErrorResult = new ErrorMessageResult("Missing API Key");
}
}
// We don't want to add challange as I am using keys authenticaiton
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.FromResult(0);
}
}
Extract API Key
public static string ExtractApiKey(HttpRequestMessage request)
{
if (!request.Headers.TryGetValues("x-api-key", out IEnumerable<string> keys))
return string.Empty;
return keys.First();
}
The solution was to include "targetFramework=4.5" in the web.config as commented by #Alfredo and more details in https://stackoverflow.com/a/32338414/3973463

Return custom HTTP code from ActionFilterAttribute

I use the code below to throttle my ASP.NET Web Api:
public class Throttle : ActionFilterAttribute
{
public override async Task OnActionExecutingAsync(HttpActionContext context, CancellationToken cancellationToken)
{
// ...
if (throttle)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
}
}
}
However, I cannot return error code 429, because it's not in HttpStatusCode enum. Is there a way to return a custom error code?
I found this over here.
var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
ReasonPhrase = "Too Many Requests",
Content = new StringContent(string.Format(CultureInfo.InvariantCulture, "Rate limit reached. Reset in {0} seconds.", data.ResetSeconds))
};
response.Headers.Add("Retry-After", data.ResetSeconds.ToString(CultureInfo.InvariantCulture));
actionContext.Response = response;
Hope this helps
This is what I did based on another response on StackOverflow.
Create Class (in controller file worked for me)
public class TooManyRequests : IHttpActionResult
{
public TooManyRequests()
{
}
public TooManyRequests(string message)
{
Message = message;
}
public string Message { get; private set; }
public HttpResponseMessage Execute()
{
HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)429);
if (!string.IsNullOrEmpty(Message))
{
response.Content = new StringContent(Message); // Put the message in the response body (text/plain content).
}
return response;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
}
Use in controller
public IHttpActionResult Get()
{
// with message
return new TooManyRequests("Limited to 5 request per day. Come back tomorrow.");
// without message
// return new TooManyRequests();
}

Is it possible to use and httphandler to download image, serve to browser and repeat process?

I was wondering if it is possible to use an httphandler to download an image, serve that image to the browser and then do it again.
I currently have access to a url that produces a snapshot image from an ip camera that I would like to continue to pull from. Essentially making a slide show of the snapshots indefinitely.
I have already figured out how to download the image and display it. The next step would to, for a lack of better terms, recursively repeat the process.
I certainly can do this with Ajax calls from the client but would much rather remove handle it at the server.
Thanks,
Chad
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Web;
using System.Threading;
namespace Something.App_Code
{
class CameraSnapshotHandler : IHttpAsyncHandler
{
public bool IsReusable { get { return false; } }
public CameraSnapshotHandler() { }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
{
SnapshotAsynchOperation asynch = new SnapshotAsynchOperation(cb, context, extraData);
asynch.StartAsyncWork();
return asynch;
}
public void EndProcessRequest(IAsyncResult result) { }
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
}
class SnapshotAsynchOperation : IAsyncResult
{
private bool _completed;
private Object _state;
private AsyncCallback _callback;
private HttpContext _context;
bool IAsyncResult.IsCompleted { get { return _completed; } }
WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
Object IAsyncResult.AsyncState { get { return _state; } }
bool IAsyncResult.CompletedSynchronously { get { return false; } }
public SnapshotAsynchOperation(AsyncCallback callback, HttpContext context, Object state)
{
_callback = callback;
_context = context;
_state = state;
_completed = false;
}
public void StartAsyncWork()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
}
private void StartAsyncTask(Object workItemState)
{
using (var client = new WebClient())
{
// Get Json data
string username;
string password;
using (var credClient = new WebClient())
{
dynamic stuff = JObject.Parse(credClient.DownloadString(new Uri("http://www.some-url.com/servicestack/equipment-credentials.json?equipmentId=" + _context.Request.QueryString["id"])));
username = stuff.Username;
password = stuff.Password;
}
// Wait until we have full buffer before displaying
_context.Response.BufferOutput = true;
// Set content type to match
_context.Response.ContentType = "image/png";
// Digest Authenticate
client.Credentials = new NetworkCredential(username, password);
// Download into bit array
byte[] content = client.DownloadData("http://some-url/cgi/image.php?type=snapshot");
// Output stream to client
_context.Response.OutputStream.Write(content, 0, content.Length);
}
_completed = true;
_callback(this);
}
}
}

ASP.NET async handler content-type not sent

I have this async handler
public sealed class ImageTransferHandler : IHttpAsyncHandler
{
public bool IsReusable { get { return false; } }
public ImageTransferHandler()
{
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
{
string url = context.Server.UrlDecode(context.Request.QueryString["url"]);
ImageTransferOperation ito = new ImageTransferOperation(cb, context, extraData);
ito.Start(url);
return ito;
}
public void EndProcessRequest(IAsyncResult result)
{
}
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
private class ImageTransferOperation : IAsyncResult
{
private Object state;
private bool isCompleted;
private AsyncCallback cb;
private HttpContext context;
public WaitHandle AsyncWaitHandle
{
get { return null; }
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return isCompleted; }
}
public Object AsyncState
{
get { return state; }
}
public ImageTransferOperation(AsyncCallback cb, HttpContext context, Object state)
{
this.cb = cb;
this.context = context;
this.state = state;
this.isCompleted = false;
}
public void Start(string url)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartTransfer), url);
}
private void StartTransfer(Object state)
{
string url = (string)state;
System.Net.WebClient wc = new System.Net.WebClient();
byte[] bytes = wc.DownloadData(url);
context.Response.Headers.Add("Content-Type", "image/jpeg");
context.Response.Headers.Add("Content-Length", bytes.Length.ToString());
context.Response.BinaryWrite(bytes);
isCompleted = true;
cb(this);
}
}
}
Everything works except that the "Content-Type" header not sent.
I tried to send it both with
context.Response.Headers.Add("Content-Type", "image/jpeg");
and
context.Response.Headers["Content-Type"] = "image/jpeg";
What do I do wrong?
Use Response.ContentType. Glad that worked for you :)

Resources