Are webhooks similar to asp.net handler.ashx page - c#

i have a requirement to create a callback webhook that will notify my server of an event. I'm new to webhooks but can this just be achieved with a good old asp.net handler.ashx page on my website? Or does this need to be written with the new webhook functionality/nuget packages microsoft offers?
an example would be
public class MyHandle : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
}
catch (ex)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Related

Implementing OnActionExecuted on a custom ActionFilter

I'm currently trying to implement request logging for my WebAPI project. We're changing this to be async up and down. Consider the following example from our old action filter:
public class LogRequestActionFilter : ActionFilterAttribute
{
private ILogRepository _logRepository;
private RequestLogEntity _requestLogEntity;
public override void OnActionExecuting(HttpActionContext actionContext)
{
_logRepository = (ILogRepository)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ILogRepository));
_requestLogEntity = new RequestLogEntity
{
LogDate = DateTime.UtcNow,
Success = false
};
_logRepository.Add(_requestLogEntity);
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
Exception exception = actionExecutedContext.Exception;
if (exception == null)
{
_requestLogEntity.Success = true;
}
else
{
_requestLogEntity.ErrorMessage = exception.Message;
}
_logRepository.Update(_requestLogEntity);
}
}
I'm trying to get away from using a service locator in my filters, by using passive attributes and filter dispatchers. I've been following this example from Steven (the author of SimpleInjector). This is great for some of my other filters, and it works like a charm, I've managed to use this article to make a passive authorisation attribute/filter for example.
But now it's apparent that using this I lose the ability to capture the request when it is finished, ie. OnActionExecuted.

Adding a response header in an ExceptionFilterAttribute in ASP .Net Core

I'm trying to add a header to responses from a .Net core Web API when an exception occurs.
I'm using an ExceptionFilterAttribute...
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
base.OnException(context);
}
}
For some reason the header is not sent to the client. I'm guessing this is something to do with responses already being formed at this point so they can't be changed?
I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers. This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.
What should I change to get this to work?
Try this,
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var correlationId = "12345";
// DO OTHER STUFF
context.HttpContext.Response.OnStarting(() =>
{
context.HttpContext.Response.Headers.Add("CorrelationId", correlationId);
return Task.CompletedTask;
});
}
}
Explicitly set context.Result to write output from an exception filter:
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.Headers.Add("CorrelationId", new string[] { "12345" });
context.Result = new ObjectResult(null) { StatusCode = 500 };
context.ExceptionHandled = true;
base.OnException(context);
}
This will add the header to the actual response.

Why does HttpContext.AcceptWebSocketRequest function make an error when it gets an instance?

According to some samples in the internet and this guide I created a connection of webSocket .
public class sockets: IHttpHandler {
public bool IsReusable {
get {
throw new NotImplementedException();
}
}
public void ProcessRequest(HttpContext context) {
if (context.IsWebSocketRequest) {
context.AcceptWebSocketRequest(new socketHandler());
}
}
}
public class socketHandler: WebSocketHandler {
public socketHandler(): base(null) {}
}
There is an error in the line-
context.AcceptWebSocketRequest(new socketHandler());
the error:
Argument 1: cannot convert from 'socketHandler' to
'System.Func(System.Web.WebSockets.AspNetWebSocketContext,System.Threading.Tasks.Task)'
Can anyone help me?
The AcceptWebSocketRequest takes a method as argument, not a class instance. You code should look something like this:
public void ProcessRequest(HttpContext context) {
if (context.IsWebSocketRequest) {
context.AcceptWebSocketRequest(HandleWebSocket);
}
}
private Task HandleWebSocket(WebSocketContext wsContext)
{
// Do something useful
}
You are referencing a function from System.Web while attempting to use a function from Microsoft.Web.WebSockets.
Add the appropriate reference and it will work.

Sending Elmah Mvc error generated Id (ErrorId) to client

I´m using Elmah.MVC on my project.
I created that error handler to generate a json response to client :
public class OnHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
// Ajax
if (context.HttpContext.Request.IsAjaxRequest())
{
// Need create a Json result with generated Elmah error Id ?!?
// How can I get that Id?
context.ExceptionHandled = true;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
context.HttpContext.Response.StatusCode = error;
}
else
{
base.OnException(context);
}
}
}
I need that Id (ErrorId od db) that elmah generated automatically.
Thanks

Determine if request is PartialView or AJAX request in ASP.NET MVC 3

I have to give access rigths to the users of a website.
I am doing the filtering here:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
The problem is that I cannot distinguish full View request such as 'Index' from PartialViewRequests or AJAX calls requests.
Therefore the page 'Index' has access but the 'PartialViewGridViewForIndex' does not have access.
The property ControllerContext.IsChildAction does not help either.
You could use the IsAjaxRequest extension method to determine if an AJAX request was used to invoke this controller action:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// the controller action was invoked with an AJAX request
}
}
You can extend HttpRequestExtensions in asp.net Core 2 as below
public static class HttpRequestExtensions
{
private const string RequestedWithHeader = "X-Requested-With";
private const string XmlHttpRequest = "XMLHttpRequest";
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (request.Headers != null)
{
return request.Headers[RequestedWithHeader] == XmlHttpRequest;
}
return false;
}
}
And use it as
if (!Request.IsAjaxRequest())
{
//----
}
else
{
// -------
}
I would create an Authorization filter by extending the AuthorizeAttribute. I would then put my code in the OnAuthorize override. In the FilterContext object you can look at FilterContext.ActionDescriptor.MethodInfo.ReturnType.Name. For a partial view this will be PartialViewResult.

Categories