Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can WebApi handlers access the context? #14

Closed
VictorioBerra opened this issue Nov 13, 2019 · 3 comments
Closed

Can WebApi handlers access the context? #14

VictorioBerra opened this issue Nov 13, 2019 · 3 comments

Comments

@VictorioBerra
Copy link

@VictorioBerra VictorioBerra commented Nov 13, 2019

https://convey-stack.github.io/documentation/Web-API/

Docs show an endpoint like this:

.Post<AddParcel>("parcels", (req, ctx) => ctx.Response.Created($"parcels/{req.ParcelId}"))))

And then they show a handler but it doesnt appear that you can get to HttpContext in a handler.

@spetz

This comment has been minimized.

Copy link
Member

@spetz spetz commented Nov 13, 2019

Do you mean that you can't access HttpContext in the lambda expression or something else is wrong?

@GooRiOn

This comment has been minimized.

Copy link
Member

@GooRiOn GooRiOn commented Nov 13, 2019

@VictorioBerra there's a an accessor for that purpose inside .NET Core called IHttpContextAccessor. This will allow you to access the context (it's build on top of AsyncLocal<T>) so it's different according to the async method context. However I'd recommend wrapping this in some sort of abstraction to avoid leaking the HTTP-related stuff into the handlers.

@VictorioBerra

This comment has been minimized.

Copy link
Author

@VictorioBerra VictorioBerra commented Nov 13, 2019

@GooRiOn ahhh I can just inject IHttpContextAccessor (or rather an abstraction). That makes much more sense.

I am unfamiliar with AsyncLocal<T> but I get the general concept of accessing IHttpContextAccessor in a service during a request.

@spetz thanks for the quick reply, @GooRiOn answered the question for me, I was more or less thinking that there would be an overload of HandleAsync that exposed the context. IE:

public class DeleteParcel : IRequest
{
    public Guid ParcelId { get; }

    public DeleteParcel(Guid parcelId)
    {
        ParcelId = parcelId;
    }
}

public class DeleteParcelHandler : IRequestHandler<DeleteParcel, int>
{
    public async Task HandleAsync(DeleteParcel request, HttpContext context)
    {
        // Deleted a parcel, let's return its ID.
        return ctx.Response.Created($"parcels/{request.ParcelId}");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.