Setting ServiceStack Cookie Domain in Web.Config Causes Session Id to Change on Every Request

删除回忆录丶 提交于 2019-12-02 03:24:28

This doesn't look like a ServiceStack issue, but rather a problem with your browser not accepting the returned cookie because your test domains are invalid choices.

localhost is not a valid cookie domain:

You shouldn't be setting the domain to localhost, as this is not valid cookie domain. For a cookie domain to be considered valid it must have a . in it. So when working with localhost the domain value must be null.

IP addresses are not valid cookie domains:

You cannot use an IP address as a cookie domain. So setting 127.0.0.1 can be considered invalid by the browser.

Hosts file:

You said you setup test.com to point to 127.0.0.1 in your hosts file. Given that your ServiceStack service is listening on the loopback address then the domain test.com should work for the service, but you would have to reflect that in the configuration, i.e.

<system.web>
    <httpCookies domain="test.com"/>

You could alternatively configure this directly in your AppHost Configure method:

public override void Configure(Container container)
{
    Config = new HostConfig {
        RestrictAllCookiesToDomain = "test.com",
    };
}

If ServiceStack is correctly setting the cookie, which you say it is, then the problem has to be with the cookie not being accepted by the browser. You can confirm this be checking the cookies the browser is sending with the request. If you are not seeing a cookie sent back with your next request, the browser didn't accept them. You have to ensure that you are making requests from http://test.com and not from localhost or 127.0.0.1.

Thanks Scott, this was the ticket - winds up I found similar info when expanding my search past ServiceStack.

The only other trick was to get Visual Studio to use a custom domain instead of the standard 'localhost' when debugging locally (which explains why the session was being regenerated on each request).

There are other threads that show how to do this but no examples outside of the standard port 80. So here we go:

  • add a line to the hosts file: 127.0.0.1 my.test.com
  • open IISExpress config (C:\Users\someuser\Documents\IISExpress\config\applicationHost.config), find the section for your project and alter it similar to this: <binding protocol="http" bindingInformation="*:1412:my.test.com" />
  • go to the project properties: set Override application url to: http://my.test.com:1412 and set start url to: http://my.test.com:1412/default (or whatever your start page or service is).

I would post a screenshot but I don't have a reputation yet :)

Running the project should now use the custom domain when debugging locally in Visual Studio using the custom domain of your choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!