我希望使用C#和Razor語法檢查cookie是否已設置。如果已定,我想表明根據變量的值呈現不同的HTML
<h2> Cookie set </h2>.
如果還沒有,我想顯示
<h2>Cookie not set</h2>
因此,審查了一些東西,我有這樣的設置cookie:
//set cookie
HttpCookie cookie = Request.Cookies.Get("stackOverflowCookie");
if(cookie == null) {
cookie = new HttpCookie("stackOverflowCookie");
cookie.Value = "Hi guys!";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
使用Razor,語法上,最好的方法是什麼來呈現我所希望的?無論我嘗試結果編譯錯誤:
@{
if(Request.Cookies["stackOverflowCookie"] == null){
//some other logic is here in my actual code, so an inline statement is not sufficient
<h2> Cookie set </h2>
@}
@{ else {
<h2> Cookie not set </h2>
@}
顯然這是可怕的看起來,它不起作用。它確實顯示了我想要的功能。如何實現此功能的最佳方式?