How to return bearer token from HttpresponseMessage Asp.net Web Api

只愿长相守 提交于 2019-12-11 12:07:52

问题


How can I return token from web api so that I can set cookie of that token in javascript? In this way I am generating token

   [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 ??
    }

回答1:


Did you try StringContent ?

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



回答2:


You can also consider including the token as a cookie in the response

[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;
}


来源:https://stackoverflow.com/questions/47130428/how-to-return-bearer-token-from-httpresponsemessage-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!