REST가 stateless라는 것을 알고 있지만 이것은 설계 상 요구 사항입니다. 기존 ASp.net Web Form 애플리케이션 인 상위 애플리케이션의 API 요청을 인증해야합니다.
이 URL에 따라 세션을 공유했습니다. http://weblogs.asp.net/lichen/sharing-session-state-over-multiple-asp-net-applications-with-asp-net-state-server
ASP.NET의 여러 웹 응용 프로그램에서 동일한 세션 ID를 유지하는 방법
http://www.codeproject.com/Articles/27090/Sharing-Session-Across-Applications
세션 공유를위한 두 응용 프로그램의 Global.asax 코드
public override void Init()
{
base.Init();
try
{
// Get the app name from config file...
string appName = ConfigurationManager.AppSettings["ApplicationName"];
Logger.LogEx(string.Format("{0} - {1}", appName, appName));
// regenerateId();
if (!string.IsNullOrEmpty(appName))
{
foreach (string moduleName in this.Modules)
{
IHttpModule module = this.Modules[moduleName];
SessionStateModule ssm = module as SessionStateModule;
Logger.LogEx(string.Format("module {0} - ssm {1}", module, ssm));
if (ssm != null)
{
FieldInfo storeInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
SessionStateStoreProviderBase store = (SessionStateStoreProviderBase)storeInfo.GetValue(ssm);
if (store == null) //In IIS7 Integrated mode, module.Init() is called later
{
FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);
FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic);
Logger.LogEx(string.Format("theRuntime {0} - appName {1}", theRuntime, appName));
appNameInfo.SetValue(theRuntime, appName);
}
else
{
Type storeType = store.GetType();
if (storeType.Name.Equals("OutOfProcSessionStateStore"))
{
FieldInfo uribaseInfo = storeType.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);
uribaseInfo.SetValue(storeType, appName);
}
}
}
}
}
}
catch (Exception ex)
{
}
}
web.cofing에서 상태 서버를 활성화했습니다.
sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:122233" cookieless="false" timeout="240" stateNetworkTimeout="3600" />
내가 자식 (Web Api2) 응용 프로그램의 부모 응용 프로그램에서 저장 / 공유 한 세션을 선택하려는 코드입니다.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
try
{
string loginMethod = "";
string sFileName = "";
string userName = "";
//string sFileExt = Strings.LCase("" + System.IO.Path.GetExtension(sender.request.filepath.ToString()));
//string serverName = HttpUtility.UrlEncode(Request.ServerVariables("SERVER_NAME"));
//ILog log1 = log4net.LogManager.GetLogger(HttpContext.Current.CurrentHandler.GetType());
if ((HttpContext.Current.Session == null || HttpContext.Current.Session["UserID"] == null) && ConfigurationManager.AppSettings["SSOEnabled"] == "1")
{
Logger.LogEx("Session is null");
userName = "" + GetDomainUserName(HttpContext.Current.User.Identity);
string domainName = "" + GetDomainName(HttpContext.Current.User.Identity);
loginMethod = "Windows Authentication";
if (!string.IsNullOrEmpty(userName))
{
Logger.LogEx("Windows userName extracted");
Logger.LogEx(userName);
Logger.Log(String.Format("Connecting to API with windows username {0}", userName));
}
else if ((HttpContext.Current.Session == null || HttpContext.Current.Session["UserID"] == null))
{
Logger.LogEx("Session is null or UserId not found, exception is thrown");
throw new HttpResponseException(System.Net.HttpStatusCode.Unauthorized);
}
else if ((HttpContext.Current.Session != null && HttpContext.Current.Session["UserID"] != null))
{
loginMethod = "User is logged in via application Login interface";
Logger.LogEx("userName is extracted from Shared Session");
userName = HttpContext.Current.Session["UserName"].ToString();
}
if (userName != null && userName != "")
{
Logger.LogEx(loginMethod);
}
else
{
Logger.LogEx("User Name is blank");
Logger.Log("User should be logged in using Application Login Interface");
throw new Exception("Unauthorized: User should be logged in using Application Login interface");
}
Logger.Log(String.Format("Start request for {0}", HttpContext.Current.Request.Url.ToString()));
}
catch (Exception ex)
{
Logger.Log(ex);
throw;
}
}
인증이 Windows로 설정되면 "HttpContext.Current.User"에 액세스 할 수 있으며 API에 액세스 할 수 있습니다.
익명 인증이 설정된 경우 동일한 배열이 작동해야합니다.이 경우 "HttpContext.Current.Session"은 Parent가 설정 한 Session 값을 유지해야하지만 Session 자체는 Null입니다.
API에서 세션을 활성화하면 Session이 null이 아니지만 Parent 앱의 값을 사용할 수 없습니다.
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
"하위 웹 API 2 앱"에서 "부모 웹 사이트"에서 설정 한 세션 변수에 액세스하는 것을 목표로합니다. 도와주세요.
내 문제에 대한 해결책을 찾았습니다!
세션은 AcquireRequestState 이벤트 바로 전에 활성화되어야합니다.
protected void Application_PostMapRequestHandler(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다