我正在尝试从角度服务将承载令牌传递给我的Web api项目
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization' : 'Bearer wYr2EBxSvQZlHgFjvWlznDJ4gNuw20r_pXBZKaCMAY3oROT5xqBiNutdjUdxWttmqdZmMy32-UlttNXosJcV7xlpVibawTKOxQRpvZK86K4AZ6ka_vzvrgPQcHXCClan0tzLmx38tLrPpLtX_y0M4nM7KzJ1NDoKqRJf6RtCIYWY0HUaDU8WE6qNMCrysOWLichS5zMBTSyNZVzSYTpIo4VxCqlAd_hmeljtyb8ypZ_0i-Xf7U4gNT6EcRMCAikNqPDF7ROy84qybDDgyx3CvcPC_JbvbnphrBuNVzRdiwu5MvN81gxNYiPY4Mp-HtJV2FZhnIwn_nQW3bFJVW4OZ5NW3IqLzoRI5HvllUnqfs0Jl4bNf8Pa5uSLDSG6rLAVps9QTWYlLtI-U4uRrOgespLPVlg7aYAt-vnSQkgMyJJI66wdPjuaXfjdIg0hZVTPihWt7bnyXB0mtvYa7QxXsW3KqIOt4OimTaYZRdt8-rQWvSzo2-Z8TY0q9W0crIVU'
})
};
LikeImage(imageId: number): Observable<number> {
return this.http.post<number>('api/images/1/likes',httpOptions );
}
我在控制器中的方法正在关注
[Route("{imageId}/likes")]
[Authorize]
public IHttpActionResult LikeImage(int imageId)
{
if (imageId <= 0)
{
return BadRequest(message: "Invalid image id");
}
string userId = HttpContext.Current.User.Identity.GetUserId();
(and etc.)
}
问题是,当我使用Fiddler / Postman时,所有工作都有效,并且userId
显示了真实的用户ID,但是当我尝试从角度项目GetUserId()
传递相同令牌时返回null
使用尖头时的标题
POST /api/images/1/likes HTTP/1.1
Host: localhost:56688
Connection: keep-alive
Content-Length: 52
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Content-Type: application/json
Referer: http://localhost:4200/images
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
使用邮递员/提琴手时的标题
POST /api/images/2/likes HTTP/1.1
cache-control: no-cache
Postman-Token: 67afdaf3-d853-42a1-ad4b-f739d026a300
Authorization: Bearer (same access_token)
User-Agent: PostmanRuntime/7.2.0
Accept: */*
Host: localhost:56688
accept-encoding: gzip, deflate
content-length: 0
Connection: keep-alive
答案 0 :(得分:2)
您的post方法将body
作为第二个参数,然后将选项(headers
)作为第三个参数。 See definition
但是,我鼓励您使用拦截器,就像您的方法一样,您必须预先向每个请求添加标头,但这并不是很理想!
Take a look here,详细说明了如何设置自己的计算机。
实质上,您会这样做
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modified = req.clone({setHeaders: {Authorization: 'Bearer mytokengoeshere'}});
return next.handle(modified);
}
}
在您的app.module
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}]
希望这会有所帮助。