Coder Social home page Coder Social logo

cypressious / httpproblemdetails Goto Github PK

View Code? Open in Web Editor NEW

This project forked from lvermeulen/httpproblemdetails

0.0 2.0 0.0 62 KB

A library to render problem details as specified by RFC 7808 at https://tools.ietf.org/rfc/rfc7807.txt, with implementations for WebApi, AspNetCore and Nancy.

License: MIT License

PowerShell 30.58% C# 69.42%

httpproblemdetails's Introduction

Icon

HttpProblemDetails Build status license NuGet Coverage Status Dependency Status Join the chat at https://gitter.im/lvermeulen/Equalizer

A library to render problem details as specified by RFC 7807 at https://tools.ietf.org/rfc/rfc7807.txt, with implementations for WebApi, AspNetCore and Nancy.

Features:

  • Web Api ExceptionFilterAttribute
  • AspNetCore ExceptionFilter
  • AspNetCore Middleware
  • Nancy pipelines extension

Usage:

Implement interface IHttpProblemDetailException in your exceptions, which is an exception with an IHttpProblemDetail. The IHttpProblemDetail carries the fields required by the RFC and will be rendered in your HTTP response.

The tests use exception InsufficientCashException with problem detail InsufficientCashProblem following the example in the RFC.

  • AspNetCore ExceptionFilter:

Step 1: Register the exception filter in your Startup class

    public class ExceptionFilterStartup
    {
        private ILoggerFactory _loggerFactory;

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new HttpProblemDetailsExceptionFilter(_loggerFactory));
            });
        }
    }

Step 2: Throw an exception with a problem detail in your controller

    public class PaymentController : Controller
    {
        [Route("/payment/{account}")]
        public string GetPayment(string account)
        {
            if (account == "12345")
            {
                var problemDetail = new InsufficientCashProblem
                {
                    Type = new Uri("https://example.com/probs/out-of-credit"),
                    Title = "You do not have enough credit.",
                    Status = 403,
                    Detail = "Your current balance is 30, but that costs 50.",
                    Instance = new Uri("/account/12345/msgs/abc", UriKind.Relative)
                };
                throw new InsufficientCashException(problemDetail.Status, problemDetail);
            }

            return "OK";
        }
    }
  • AspNetCore Middleware:

Step 1: Use the middleware in your Startup class

    public class MiddlewareStartup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseHttpProblemDetails();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
    }

Step 2: Throw an exception with a problem detail in your controller

    public class PaymentController : Controller
    {
        [Route("/payment/{account}")]
        public string GetPayment(string account)
        {
            if (account == "12345")
            {
                var problemDetail = new InsufficientCashProblem
                {
                    Type = new Uri("https://example.com/probs/out-of-credit"),
                    Title = "You do not have enough credit.",
                    Status = 403,
                    Detail = "Your current balance is 30, but that costs 50.",
                    Instance = new Uri("/account/12345/msgs/abc", UriKind.Relative)
                };
                throw new InsufficientCashException(problemDetail.Status, problemDetail);
            }

            return "OK";
        }
    }
  • Nancy pipelines extension:

Step 1: Enable the extension

    public class SampleBootstrapper : DefaultNancyBootstrapper
    {
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            HttpProblemDetails.Enable(pipelines, container.Resolve<IResponseNegotiator>());
        }
    }

Step 2: Throw an exception with a problem detail in your module

    public class PaymentModule : NancyModule
    {
        public PaymentModule()
        {
            Get("/payment/{account}", async args =>
            {
                if (args.account == "12345")
                {
                    var problemDetail = new InsufficientCashProblem
                    {
                        Type = new Uri("https://example.com/probs/out-of-credit"),
                        Title = "You do not have enough credit.",
                        Status = 403,
                        Detail = "Your current balance is 30, but that costs 50.",
                        Instance = new Uri("/account/12345/msgs/abc", UriKind.Relative)
                    };
                    throw new InsufficientCashException(problemDetail.Status, problemDetail);
                }

                return await Response
                    .AsText("OK")
                    .WithStatusCode(HttpStatusCode.OK);
            });
        }
    }
  • Web Api ExceptionFilterAttribute

Step 1: Add the exception filter to your configuration, or apply the attribute to a controller or method

Configuration:

	GlobalConfiguration.Configuration.Filters.Add(
	    new HttpProblemDetailsExceptionFilterAttribute());

Controller or method:

	[HttpProblemDetailsExceptionFilter]
    public class PaymentController : ApiController
    {
        [Route("/payment/{account}")]
		[HttpProblemDetailsExceptionFilter]
        public string GetPayment(string account)
        {
			...
		}
	}

Step 2: Throw an exception with a problem detail in your controller

    public class PaymentController : ApiController
    {
        [Route("/payment/{account}")]
        public string GetPayment(string account)
        {
            if (account == "12345")
            {
                var problemDetail = new InsufficientCashProblem
                {
                    Type = new Uri("https://example.com/probs/out-of-credit"),
                    Title = "You do not have enough credit.",
                    Status = 403,
                    Detail = "Your current balance is 30, but that costs 50.",
                    Instance = new Uri("/account/12345/msgs/abc", UriKind.Relative)
                };
                throw new InsufficientCashException(problemDetail.Status, problemDetail);
            }

            return "OK";
        }
    }

Thanks

httpproblemdetails's People

Contributors

lvermeulen avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.