WebAPI不会通过控制器维护FormsAuthentication

时间:2015-06-24 14:46:51

标签: c# asp.net api controller

情况就是这样:

我拥有一个AccountController,它继承自ApiController,看起来像这样

    [HttpPost]
    [ActionName("Login")]
    public HttpResponseMessage Login()
    {
        string emailOrUsername = base.Request.GetQueryNameValuePairs().ElementAt(0).Value;
        FormsAuthentication.SetAuthCookie(emailOrUsername, false);
        return Request.CreateResponse<string>(HttpStatusCode.OK, emailOrUsername);
    }
    [HttpGet]
    [Authorize]
    [ActionName("Logout")]
    public HttpResponseMessage Logout()
    {
        FormsAuthentication.SignOut();
        return Request.CreateResponse<string>(HttpStatusCode.OK, "Hope to see you again!");
    }

我还拥有一个MessageController,它也继承自ApiController,如下所示:

    [HttpPost]
    [Authorize]
    [ActionName("ReceiveMessage")]
    public HttpResponseMessage ReceiveMessage()
    {
        return Request.CreateResponse<string>(HttpStatusCode.OK, "Successfully received your message");
    }

因此,AccountController工作正常,我登录并能够注销。 这是棘手和令人困惑的部分开始的地方。当我在同一台计算机(localhost)上进行测试时,我可以在获得授权后访问ReceiveMessage。 到目前为止一切都很好。

我现在编辑了Documents \ IISExpress \ config \ applicationhost.config并编辑了绑定: 绑定协议=&#34; http&#34; bindingInformation =&#34;:60967:&#34;

所以我可以从其他设备访问我的WebApi。我可以登录和注销,但是我无法从这个新设备访问ReceiveMessage(带登录) - 在本地主机上我可以做任何我想做的事。

我做错了什么? (这是一个示例,我计划让多个用户连接到api,因此在某处不能选择静态var)

1 个答案:

答案 0 :(得分:0)

浏览器明智的工作正常,@ charlie Brown是正确的,问题与cookie有关 - 我是从一个统一的应用程序进行访问