Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count of cookies is zero after page refresh and angular routing with url rewrite

I am using angular Spa template with .net core 2.0 and angular 4.

I am getting zero count of cookies after page refresh. and in fact I am not getting anything in HttpContext after page gets refreshed.

Here is my cookie in browser. enter image description here

it's working fine if I uses angular system menu.

Now, here is my code for getting cookie in back end.

    private string GetCookie(HttpContext httpContext, string cookieName)
    {
        var rqstCookie = httpContext.Request.Cookies[cookieName];

        return !string.IsNullOrEmpty(rqstCookie) ? rqstCookie : null;
    }

one important thing is that when I click in menu, it loads component and service files and then it requests to C# controller with all headers and options. but when I refresh page this whole process get skipped, so I think this options are not delivered to back end and that's why my cookies are empty.

in my other applications, I have used url rewrite for same kind of issues and it worked over there but here because this application is angular spa template, url rewrite is not working.

I have also tried to setup the url rewrite, the same way I did in my old applications, but it gives me error. here is the link of the url rewrite module that I followed. https://stackoverflow.com/a/26152011/5816119

I have updated cookies to Session cookie but it's also not working.

can you guide me how to get all the cookies and other data even when user refreshes page. thanks...

like image 519
Bharat Avatar asked Feb 19 '18 08:02

Bharat


2 Answers

It was a angular side issue.

when I added APP_BASE_HREF in my routing module, it suddenly started working.

https://stackoverflow.com/a/34535256/5816119

Here is my code,

import { APP_BASE_HREF } from "@angular/common";

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        ...
        ],
    imports: [
        HttpModule,
        ...,
        RouterModule.forRoot([
            { path: "", redirectTo: "home", pathMatch: "full" },
            { path: "**", redirectTo: "home" }
        ], { useHash: true }),
    ],
    providers: [
        { provide: APP_BASE_HREF, useValue: '/' },
    ],
};

So, it's basically a hashing technology in router side, and seems I was missing this provider in my app too.

like image 131
Bharat Avatar answered Nov 19 '22 01:11

Bharat


try to specify when the cookie will expire by using this code when writing cookie

 option.Expires = DateTime.Now.AddDays(x);

 Response.Cookies.Append(cookiename, cookievalue, option);

you can modify AddDays(x) to the number of days you want

like image 40
Mohamad Elnaqeeb Avatar answered Nov 19 '22 00:11

Mohamad Elnaqeeb