尝试在我的开发博客上上传帖子时遇到问题。我正在尝试使用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?}");
});
}
}
}
因为我不知道错误在哪里。但是我需要知道405错误的来源。
谢谢。
答案 0 :(得分:0)
检查您的创建视图(Create.cshtml),以确保表单标签中的asp-action =“ CreatePostAsync”。
如果这不是问题,请同时包含您的查看代码。
还要在CreatePostAsync处设置一个断点,然后继续观察错误发生的位置。动作可能没有被触发。也就是说,您的断点也不会被触发。
很少有其他可以帮助解决问题和/或解决问题的方法:
答案 1 :(得分:0)
“超文本传输协议(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)