【问题标题】:How Can Get Session With SessionId?如何使用 SessionId 获取会话?
【发布时间】:2020-07-22 20:41:22
【问题描述】:

我使用 ASP.NET MVC。我有个问题。我将变量设置为会话,并请求不属于我的 Web 服务。然后 Web 服务向我的服务器发出 HttpPost 请求。 它不会向我的服务器发送 cookie,所以我失去了会话。

我想我可以将我的sessionid 保存到数据库中,然后我可以用这个 ID 恢复我的会话。但我无法得到任何解决方案。

你有什么建议?

public ActionResult SomeAction(){
    mySettingService.saveSessionIdToDb(someToken, Session.SessionID);

    var myPaymentFormObj = FormInit.Create(request, options);
    myPaymentFormObj.DoRequest(); //it's callback to my another action with a token
}


[HttpPost]
public ActionView MyCallBack(string someToken){
    //here is our app generates new session id and i lost my session because other server doesn't send me session id.
    //i need to read session id from db and i can get my session maybe.

    var mySessionId = mySettingService.getSessionIdFromDb(someToken);

    //how can i start session like this?
    Session.SessionID = mySessionId;
}

【问题讨论】:

  • 您发布的SomeAction 是否负责将请求发送到您提到的网络服务器?

标签: c# asp.net asp.net-mvc session transactions


【解决方案1】:

您描述的问题似乎与维护分布式事务有关。 为了更好地描述它,您的应用程序是服务 A,而 webServer 是服务 B。 您可以执行一个操作来保存对数据库 A 的一些更改,包括会话内容,然后您向服务 B 发送调用,该调用还可以保存对其数据库的一些更改或执行一系列其他操作,但在这种情况下,您不在乎它是如何工作的,你只关心你通过回调得到什么样的响应。应该有一个选项可以发送某种独特的东西,例如userEmailtransactionId,您可以通过回调方法返回以识别交易。

我建议你做的事情是这样的

[HttpPost]
public ActionResult SendBlah(BlahData data){
    var transactionId = Guid.NetGuid();
    _sessionService.Create(transactionId, dataYouWantToStore)
    _webServiceB.SendBlah(transactionId, data, token);
    //optionally return info about call status / do other stuff
}

//or this can be of type HttpGet
[HttpPost]
public ActionView MyCallBack(string someToken, string tranactionId){
    var sessionData = _sessionService.Get(tranactionId) 
    //do other stuff
}

如果需要并且您正在使用例如JWT 您可以将transactionId/emailAddress/etc. 存储在那里并阅读它。 顺便提一句。将会话存储在数据库中总是更安全,而不是使用一些缓存对象或中继 cookie 或 javascript 对象等。 此外,最好注意要存储在数据库中的 Session 表中的数据量。我个人会专注于存储 ID 和给定项目的状态等内容。

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2013-04-12
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多