【问题标题】:How to return bearer token from HttpresponseMessage Asp.net Web Api如何从 HttpresponseMessage Asp.net Web Api 返回不记名令牌
【发布时间】:2023-03-11 15:29:01
【问题描述】:

如何从 web api 返回令牌,以便我可以在 javascript 中设置该令牌的 cookie? 这样我正在生成令牌

   [Route("api/agency/login")]
    [HttpPost]
    public HttpResponseMessage loginApi([FromBody] Users UserObj)
    {
           var tokanObj = method.AccessToken(UserObj.username, UserObj.Password, "password");

   //How to return this token ??
    }

【问题讨论】:

  • 您使用的是哪个 Web api 版本(.net 核心或具有完整 .net 框架的 Web Api 2)?
  • Asp.net web api2
  • 从HttpResponseMessage改成String(或者token对象是什么类型),直接返回tokenObj
  • 什么是tokenObj类型?
  • 对象类型为 var

标签: c# asp.net-mvc asp.net-web-api2


【解决方案1】:

你试过StringContent吗?

return new HttpResponseMessage( HttpStatusCode.OK ) 
{
    Content =  new StringContent( "Your token here" ) 
};

【讨论】:

【解决方案2】:

您还可以考虑将令牌作为 cookie 包含在响应中

[Route("api/agency/login")]
[HttpPost]
public HttpResponseMessage loginApi([FromBody] Users UserObj) {
    var tokanObj = method.AccessToken(UserObj.username, UserObj.Password, "password");

    var response = Request.CreateResponse(HttpStatusCode.OK);
    //use what every you want as the key for the cookie
    var cookie = new CookieHeaderValue("auth_token_key", tokenObj);

    //...set cookie values as needed

    response.Headers.AddCookies(new[] { cookie });

    return response;
}

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 2018-01-24
    • 2023-04-02
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2016-04-07
    • 2012-12-13
    • 2016-12-17
    相关资源
    最近更新 更多