1

ASP.NET Web フォームとフォーム認証で ServiceStack を使用しています。サービス呼び出しごとに次のロジックが必要です。

//-- on 'Begin Request' --
var identity = HttpContext.Current.User.Identity;
if (!identity.IsAuthenticated)
    throw new UnauthorizedAccessException();
var user = //lookup user in Db using identity.Name
new UserScope(user) //store this somewhere(?) 

//-- on 'End Request' --
var scope = //get user scope
scope.Dispose();

このロジックはどこに行くべきですか?Begin Request部分は、リクエスト フィルターで処理できるように見えますが、それが最適な場所であるとは確信していません。どこUserScopeに保管・処分すればよいですか?同じスレッドで作成および破棄する必要があります。

アップデート

/をサブクラス化ServiceRunner<TRequest>してオーバーライドしました。OnBeforeExecuteOnAfterExecute

public override void OnBeforeExecute(IRequestContext requestContext, TRequest request) {
    if (!IsLoginRequest()) {
        var identity = HttpContext.Current.User.Identity;
        if (identity.IsAuthenticated) {
            var user = User.GetByUserName(identity.Name);
            if (user != null) {
                requestContext.SetItem(USER_SCOPE_KEY, new UserScope(user));
                return;
            }
        }
        throw new UnauthorizedAccessException();
    }
}

public override object OnAfterExecute(IRequestContext requestContext, object response) {
    if (!IsLoginRequest()) {
        var userScope = (UserScope)requestContext.GetItem(USER_SCOPE_KEY);
        if (userScope != null)
            userScope.Dispose();
    }
    return response;
}

とオーバーライドAppHost.CreateServiceRunner:

public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) {
    return new MyServiceRunner<TRequest>(this, actionContext);
}

のソースをServiceRunner見ると、OnBeforeExecute/OnAfterExecuteは同じスレッドで実行する必要があるようです。これが機能しない理由はありますか?

4

1 に答える 1