问题描述
尝试在我的开发博客上上传帖子时遇到问题。我正在尝试使用MVC框架上传帖子。我正在尝试遵循有关如何构建博客的大量指南。
这是Post课
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectWebApp.Models
{
public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PostID { get; set; }
[required]
public string Title { get; set; }
[required]
public string Content { get; set; }
public string Author { get; set; }
public int Likes { get; set; }
[required]
public DateTime DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}
}
这是BlogDBContext:
using Project.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectBlogWebApp.Data
{
public class BlogDbContext : DbContext
{
public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options)
{
Database.EnsureDeleted();
if (Database.EnsureCreated() == true)
{
Database.EnsureCreated();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>().HasKey(p => new {p.PostID,p.TagID});
modelBuilder.Entity<PostTag>().HasOne(pt => pt.Post).WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostID);
modelBuilder.Entity<PostTag>().HasOne(pt => pt.Tag).WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagID);
}
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
}
}
这是PostController类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ProjectWebApp.Data;
using ProjectWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
namespace ProjectWebApp.Controllers
{
public class PostController : Controller
{
private BlogDbContext _dbBlogContext;
public PostController(BlogDbContext dbContext)
{
_dbBlogContext = dbContext;
}
public IActionResult Index()
{
var postList = _dbBlogContext.Posts.ToList();
return View(postList);
}
[HttpGet,Route("Create")]
public IActionResult Create()
{
return View(new Post());
}
[HttpGet,Route("Edit")]
public IActionResult Edit()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreatePostAsync([Bind("Title","Content")] Post post)
{
try
{
post.Likes = 0;
post.DateCreated = DateTime.Now;
post.Author = "Leonard Morrison";
_dbBlogContext.Add(post);
await _dbBlogContext.SaveChangesAsync();
}
catch (dbupdateException)
{
ModelState.TryAddModelError( "Error: Post was not added properly!","Sorry,the Post was not added properly. Please let me kNow if this problem persists");
}
return View(post);
}
[HttpGet]
public IActionResult Show(int ID)
{
var post = getPost(ID);
return View(post);
}
[HttpGet]
public IActionResult Edit(int ID)
{
var post = getPost(ID);
return View(post);
}
[HttpPatch]
public IActionResult Update(int id)
{
var post = _dbBlogContext.Posts.Find(id);
_dbBlogContext.Posts.Update(post);
return RedirectToAction("Index");
}
[HttpDelete]
public IActionResult RemovePost(int id)
{
Post deletedPost = getPost(id);
_dbBlogContext.Posts.Remove(deletedPost);
_dbBlogContext.SaveChanges();
return RedirectToAction("Index");
}
public Post getPost(int ID)
{
var post = _dbBlogContext.Posts.First(p => p.PostID == ID);
return post;
}
}
}
最后,这是启动源代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ProjectWebApp.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
namespace ProjectBlogWebApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<BlogDbContext>(options => options.UsesqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<BlogDbContext,BlogDbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//The Main EndPoint Routes
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",pattern: "{controller=Home}/{action=Index}/{id}");
});
//The Post Endpoints Routes
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "post",pattern: "{controller=Post}/{action=Index}/{title?}");
});
}
}
}
谢谢。
解决方法
检查您的创建视图(Create.cshtml),以确保表单标签中的asp-action =“ CreatePostAsync”。
如果这不是问题,请同时包含您的查看代码。
还要在CreatePostAsync处设置一个断点,然后继续观察错误发生的位置。动作可能没有被触发。也就是说,您的断点也不会被触发。
很少有其他可以帮助解决问题和/或解决问题的方法:
- BlogDbContext:OnModelCreating(),这些代码是否表示外键?只要属性名称为{TableName} Id,EF就会自动创建/映射外键。您还可以通过对ForeignKey使用[ForeignKey]属性来明确显示
- 控制器:您可以将方法和路由[HttpGet(“ Create”)]组合在一起。我敢肯定这不是问题,只是想让您知道
- Create():无需将新的Post模型传递给view(),因为您的视图已经具有“ @model Post”
- CreatePostAsync():我建议创建一个具有必要属性和验证检查的PostViewModel。使用PostViewModel作为参数。这也意味着您需要将创建视图从@model Post更新为@model PostViewModel
- CreatePostAsync():处理完成后,请始终将post方法重定向回去获取。如果有错误,只有您应该返回View()的时间才会出现。否则,用户可以垃圾邮件刷新并创建多行数据。一旦创建成功,就可以亲自尝试一下
“超文本传输协议(HTTP)405方法不允许”响应状态代码指示服务器知道该请求方法,但目标资源不支持该请求方法。
生成Url为"localhost:5001/Create"
,仅与Create Get方法匹配,而表单发送HttpPost请求,因此发生405错误。
1。您可以在表单标签上添加一个asp-action="CreatePost"
,
2。或者只是在CreatePost操作上添加相同的Route属性
[HttpPost]
[Route("Create")]
public async Task<IActionResult> CreatePostAsync([Bind("Title","Content")] Post post)