Home > Blockchain >  How to acess response (HttpResponse) outside of controller in service layer in Asp.net webapi
How to acess response (HttpResponse) outside of controller in service layer in Asp.net webapi

Time:11-05

I have a webapi where iam using repository pattern, in the service layer i have to acess the response.cookies and append few values to it and so far iam unable to figure out how to do it , it looks like the response is accessible only within the controller,can someone please teach me how to do it in service layer? i have attached the code i have so far below

        private Cart CreateCart()
        {
            string buyerId = Guid.NewGuid().ToString();
            CookieOptions cookieOptions = new CookieOptions {
                IsEssential = true,
                Expires = DateTime.Now.AddDays(30)
            };

             //unable to do this in service layer
             Response.Cookies.Append("buyerId",buyerId,cookieOptions);
             //

            Cart cart = new Cart { BuyerId = buyerId };
            context.Add(cart);
            return cart;
        }

CodePudding user response:

In your service, you can inject HttpContext to get the HttpResponse object for the current request :

public class CartService
{
    private HttpContext _httpContext;

    public CartService(HttpContext httpContext)
    {
        _httpContext = httpContext;
    }

    private Cart CreateCart()
    {
        ...
        _httpContext.Response.Cookies.Append(...)
    }
}

CodePudding user response:

While the response given to you will do the job, it is a violation of the S principle in SOLID to have the business service layer access the HTTP context because the service layer should not even know it is being handled by an HTTP server.

In other words, the controller is the sole responsible of translating data from the HTTP protocol to usable objects, and to transmit data in objects through the HTTP protocol. This is the controller's Single responsibility. By making the business service layer HTTP-aware, you have made your service layer dependant on HTTP, and you have stepped into the controller's business.

What you need to do is refactor your service response into an object that returns all the data (the calculation itself, plus the data that needs to go into the cookies), so that, at a controller level, or at a service level that's in charge of manipulating service results, the data can be sorted into the respective HTTP artifacts, namely HTTP response and cookies.

  • Related