在 asp.net MVC4 应用程序中重新连接到 Servicestack 会话 [英] Reconnecting to Servicestack session in an asp.net MVC4 application

查看:29
本文介绍了在 asp.net MVC4 应用程序中重新连接到 Servicestack 会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 asp.net mvc4 web 应用程序,它从一个用 C# 编写的 API 中使用数据数据,并托管在带有 Apache/mod_mono 的 Linux 机器上

I have an asp.net mvc4 web application that is consuming data data from an API written in C# and hosted on a Linux machine w/ Apache / mod_mono

客户端应用程序是用 C#/asp.net 编写的 - 它在不同的 Web 服务器上运行,也是 Linux/Apache/mod_mono.我不确定这些细节在这种情况下是否重要,但我认为任何背景都可能有所帮助.

The client application is written in C#/asp.net - It runs on a different web server, also Linux / Apache / mod_mono. I'm not sure if those details are important in this case, but I figured any background may help.

导致这个问题的问题:AppHostBase 实例未设置 - 帮助我获得了很多对这一切如何组合在一起有更多的了解.

The question leading up to this one: AppHostBase instance not set - Helped me gain quite a bit more understanding of how this all fits together.

我认为我现在应该问的正确问题是:一旦我在服务堆栈中(在 API 服务器上)创建了一个会话,我该如何正确地重新连接到它?

I believe the proper question I should be asking now is: Once I create a session in servicestack (On the API server), how do I properly reconnect to it?

按照之前问题中的答案,我在客户端应用程序的身份验证控制器中使用了这段代码:

Following the answers in previous questions, I've used this bit of code in my auth controller on the client application:

        var authService = AppHostBase.Resolve<AuthService>();
        authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
        var AuthResponse = authService.Authenticate(new Auth
            {
                provider = "credentials",
                UserName = user.user_id,
                Password = user.password,
                RememberMe = true
            });

这将返回一个 ResolutionException:
无法解析 ServiceStack.ServiceInterface.Auth.AuthService 类型的必需依赖项.

This returns a ResolutionException:
Required dependency of type ServiceStack.ServiceInterface.Auth.AuthService could not be resolved.

在让客户端从 asp.net 应用程序中工作时,我是否可能遗漏了一些简单的东西?

Is there something simple I might be missing when it comes to getting the client to work from within an asp.net application?

如果问题过于模糊,我深表歉意,并很乐意提供更多信息.

I apologize if the question is too vague and will happily provide any more information.

更新:
这是 AuthController - 不好意思,自从我上一篇文章以来,我一直在尝试一些东西:

Update:
This is AuthController - Excuse the mess, I've been trying a few things since my last post:

{
public partial class AuthController : BaseController
{
    JsonServiceClient client = new ServiceStack.ServiceClient.Web.JsonServiceClient("<TheAPIurl>");

    // GET: /Login/

    public ActionResult login()
    {
        if (Session["IsAuthenticated"] != null)
        {
            ViewData["Result"] = Session["IsAuthenticated"];
        }

        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult login(UserModel user)
    {
        try
        {
        var authService = AppHostBase.Resolve<AuthService>();
        authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
        var AuthResponse = authService.Authenticate(new Auth
            {
                provider = "credentials",
                UserName = user.user_id,
                Password = user.password,
                RememberMe = true
            });

            if (AuthResponse.SessionId != null)
            {
                Session["IsAuthenticated"] = true;
                Session["UserID"] = AuthResponse.UserName;
                Session["jsclient"] = client; 
                FormsAuthentication.SetAuthCookie(user.user_id, true);
                return Redirect("/default");
            }
            else
            {
                Session["IsAuthenticated"] = false;
            }

        }
        catch (Exception ex)
        {
            Session["IsAuthenticated"] = false;
        }

        return View();
    }
    protected override void ExecuteCore()
    {
        throw new NotImplementedException();
    }
}

}

推荐答案

使用本地 ServiceStack 实例进行身份验证

如果 ServiceStack 实例托管在与 MVC 相同的应用程序域中,则您只能从 ServiceStack 容器中检索自动连接的 ServiceStack 服务(或其他 IOC 依赖项),即:

Authenticating with a local ServiceStack instance

You can only retrieve an auto-wired ServiceStack service (or other IOC dependency) out from a ServiceStack Container if the ServiceStack instance is hosted within the same App Domain as MVC, i.e:

var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();

虽然用于解析另一个服务的自动连接实现的推荐代码是:

Although the recommended code for resolving the auto-wired implementation of another service is:

using (var authAservice = AppHostBase.ResolveService<AuthService>()) {
    ...
}

即由于服务可能会使用应该处置的资源.在 ServiceStack 服务中,您应该使用 base.ResolveService() 代替.

i.e. As services may make use of resources that should be disposed. Inside a ServiceStack service you should use base.ResolveService<AuthService>() instead.

因此,如果 ServiceStack 托管在与 MVC 相同的 AppDomain 中,您可以调用 Service 目录,如下所示:

So if ServiceStack hosted within the same AppDomain as MVC, you can call the Service directory, like this:

var authResponse = authService.Authenticate(new Auth {
    provider = "credentials",
    UserName = user.user_id,
    Password = user.password,
    RememberMe = true
});

使用远程 ServiceStack 实例进行身份验证

否则,如果它是远程的,您需要使用 ServiceStack 的 C# 服务客户端之一,例如:

var client = new JsonServiceClient(ServiceStackBaseUrl);
var authResponse = client.Post(new Auth {
    provider = "credentials",
    UserName = user.user_id,
    Password = user.password,
    RememberMe = true
});

将 ServiceStack SessionId 附加回原始 MVC 请求

这将通过将其附加到 ss-pid Cookie(参见 会话文档 了解更多信息).您可以将此 cookie 传递给调用 MVC 的原始浏览器:

Attaching ServiceStack SessionId back to originating MVC request

This will setup an authenticated session with that ServiceClient client, by attaching it to the ss-pid Cookie (see Session docs for more info). You can pass through this cookie to the originating browser that called MVC with:

var response = HttpContext.Current.Response.ToResponse();
response.Cookies.AddSessionCookie(
    SessionFeature.PermanentSessionId, authResponse.SessionId);

带有经过身份验证的会话的后续请求

要从 MVC 中重新附加经过远程身份验证的 ServiceStack 会话,您需要将 cookie 传递回服务客户端,例如:

Subsequent requests with the authenticated session

To re-attach with the remote authenticated ServiceStack Session from within MVC you would then need to pass the cookie back into the Service Client, e.g:

var cookie = HttpContext.Request.Cookies.Get(SessionFeature.PermanentSessionId);

var client = new JsonServiceClient(ServiceStackBaseUrl);
var cookie = new Cookie(SessionFeature.PermanentSessionId, cookie.Value);
client.CookieContainer.Add(cookie);

您可以在 Web.Config 中全局设置 cookie 域:

You can set the cookie domain, globally in the Web.Config:

<httpCookies domain="mydomain.com" />

或者在运行时使用:

cookie.Domain = "mydomain.com";

ServiceStack AuthTests.cs 集成测试还有一些其他有用的示例,展示了身份验证在 ServiceStack 中的工作原理.

The ServiceStack AuthTests.cs Integration Tests has some other useful examples showing how Authentication works in ServiceStack.

这篇关于在 asp.net MVC4 应用程序中重新连接到 Servicestack 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆