I'm having a problem trying to upload a post on my development blog. I'm trying to upload a Post by using the MVC framework. I'm trying to follow a broad number of guides as to how to build a blog.
Here's the Post class
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; }
}
}
and here's the 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; }
}
}
Here's the PostController class:
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;
}
}
}
and lastly, here's the Startup source code:
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?}");
});
}
}
}
Because I don't know where exactly the error is. But I need to where this 405 Error is coming from.
Thanks.
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response status code indicates that the request method is known by the server but is not supported by the target resource.
The generate Url is "localhost:5001/Create"
, which only match the Create Get method, while the form send a HttpPost Request, so it occurs 405 error.
1.You may add a asp-action="CreatePost"
on your form tag,
2.Or just add a same Route Attribute on your CreatePost action
[HttpPost]
[Route("Create")]
public async Task<IActionResult> CreatePostAsync([Bind("Title", "Content")] Post post)