【发布时间】:2021-01-12 08:42:11
【问题描述】:
所以我尝试使用 Blazor(不是 WebAssembly)一段时间并坚持使用重定向和标题响应。
Post.cs:
public class PostService
{
public List<Post> posts = new List<Post>()
{
new Post { ID = 1, Title = "First title", Text = "first text", Date = DateTime.Now, Author = "JohnDoe", Category = "Good" },
new Post { ID = 2, Title = "Second title", Text = "second text", Date = DateTime.Now, Author = "JohnDoe", Category = "Nice" }
};
public Task<List<Post>> GetPosts()
{
return Task.FromResult(posts);
}
public Task<Post> GetPost(int id)
{
Post post = posts.Where(x => x.ID == id).FirstOrDefault();
return Task.FromResult(post);
}
}
BlogPost.razor:
@page "/post/{ID:int}"
@using ExampleBlog.Data;
@inject PostService PostClassService
@inject NavigationManager _navigationManager
@if (post == null)
{
<p>Loading</p>
}
else
{
@post.Text
}
@code {
[Parameter]
public int ID { get; set; }
public Post post { get; set; }
public bool found { get; set; } = true;
protected override async Task OnInitializedAsync()
{
post = await PostClassService.GetPost(ID);
if (post == null)
{
found = false;
}
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
if (!found)
{
_navigationManager.NavigateTo("404");
}
}
}
}
一切都很好,如果 ID 正确,它会显示 post.Text 并正确重定向到 404 在浏览器中。
问题是服务器头返回:
curl -i --insecure https://localhost:44332/post/1
HTTP/2 200
没关系,工作正常,但如果我尝试访问不存在的实体:
curl -i --insecure https://localhost:44332/post/1234
HTTP/2 200
我需要返回 404 服务器端,以便搜索引擎等能够正确识别所有内容。
【问题讨论】: