Python请求获取的ASP.NET_SessionID无法正常使用求助
解决Python Requests中ASP.NET_SessionID会话过期问题
问题场景
你用Python requests获取ASP.NET_SessionID并用于后续请求时,碰到了这样的问题:从响应头的Set-Cookie里拿到了SessionID,但用它发起后续请求,虽然返回200状态码,却只能得到过期会话的默认数据,没法获取正确响应。但从浏览器复制的ASP.NET_SessionID,不管是在Postman还是Python请求里都能正常使用。
你的获取SessionID代码:
################### get asp session from set-cookie in response headers url = "https://finder.humana.com/finder/v1/pfp/get-language-selectors" response=session.get(url, timeout=20) print(response, url) jsonResponseHeaders = response.headers aspSession = jsonResponseHeaders['Set-Cookie'].split(';')[0] cookies=session.cookies.get_dict() print(response.headers) print('ASP.NET_SessionID:',aspSession) print(session.cookies.get_dict()) cookieString = "; ".join([str(x)+"="+str(y) for x,y in cookies.items()]) print('Cookie String:',cookieString)
后续请求代码:
################# provider plan/network request url = "https://finder.humana.com/finder/v1/pfp/get-networks-by-provider" payload = {"providerId":311778,"customerId":1,"coverageType":3} response = session.post(url, json=payload) print(response,url) print(response.headers) print(session.cookies.get_dict()) cookies=session.cookies.get_dict() cookieString = "; ".join([str(x)+"="+str(y) for x,y in cookies.items()]) print('Cookie String:',cookieString) print(response.text) print()
问题原因
- 手动拆分Cookie丢失关键属性:你手动从Set-Cookie里拆分出SessionID,但ASP.NET的Cookie包含Path、Domain、HttpOnly等属性,服务器会校验这些属性,缺失的话会判定会话无效。
- 请求头不匹配:ASP.NET站点通常会校验User-Agent等请求头,如果你的请求头和浏览器差异太大,服务器会拒绝识别生成的会话。
- Session自动管理被干扰:虽然你用了requests.Session,但手动处理Cookie的操作可能干扰了Session的自动管理逻辑。
解决方案
1. 让requests.Session自动管理Cookie
不要手动拆分Set-Cookie,Session会自动保存Cookie的所有属性,确保服务器能识别会话。
2. 模拟浏览器请求头
添加和浏览器一致的User-Agent等请求头,避免被服务器判定为非合法请求。
修改后的完整代码:
import requests # 初始化Session,设置浏览器同款User-Agent(可以从浏览器开发者工具复制) session = requests.Session() session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9' }) # 第一步请求获取有效会话,Session自动保存Cookie url = "https://finder.humana.com/finder/v1/pfp/get-language-selectors" response = session.get(url, timeout=20) print("第一次请求状态码:", response.status_code) print("当前Session中的Cookie:", session.cookies.get_dict()) # 第二步发起请求,Session自动带上所有有效Cookie url = "https://finder.humana.com/finder/v1/pfp/get-networks-by-provider" payload = {"providerId":311778,"customerId":1,"coverageType":3} response = session.post(url, json=payload) print("后续请求状态码:", response.status_code) print("响应内容:", response.text)
额外排查点
- 如果还是不行,打开浏览器开发者工具,对比第一次请求的所有请求头,把缺失的都加到Session的headers里。
- 检查浏览器请求中是否有
__RequestVerificationToken这类Cookie,有的话需要确保Session也带上,部分ASP.NET应用需要这个令牌验证请求合法性。
内容的提问来源于stack exchange,提问作者Jawad Ahmad Khan
相关产品推荐
相关产品推荐

