如何在服务器端Blazor中通过HttpContext登出 [英] How to sign out over HttpContext in server-side Blazor

查看:549
本文介绍了如何在服务器端Blazor中通过HttpContext登出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Blazor服务器端视图中访问HttpContext以手动注销.我将此行添加到Startup.cs:services.AddHttpContextAccessor();并将其注入视图中的@inject IHttpContextAccessor HttpContextAccessor. 我有一个尝试执行此代码的注销按钮:

I access the HttpContext in a Blazor server-side view to manually log out. I added this line to Startup.cs: services.AddHttpContextAccessor(); and inject it in the view with @inject IHttpContextAccessor HttpContextAccessor. I've got a log out button which tries to execute this code:

await HttpContextAccessor.HttpContext.SignOutAsync("Cookies");

但是我收到以下错误消息:

but I get the following error message:

System.InvalidOperationException: 'Headers are read-only, response has already started.'

如何防止此错误?

推荐答案

这也使我感到震惊,但是您需要注销功能位于Razor Page(不是Blazor组件)上.创建一个注销页面,并将您的注销代码放入OnGetAsync()方法中.

This tripped me up too, but you need the logout functionality to be on a Razor Page (not a Blazor component). Create a Logout page and put your logout code in the OnGetAsync() method.

然后,您的注销按钮可以链接到注销页面.

Your logout button can then link to the logout page.

http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/4316/A-Demonstration-of-Simple-Server-side-Blazor-Cookie-Authentication.aspx - this is a helpful example

这篇关于如何在服务器端Blazor中通过HttpContext登出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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