내 개발 블로그에 게시물을 업로드하는 데 문제가 있습니다. 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 오류가 발생하는 곳이 필요합니다.
감사.
HTTP (HyperText Transfer Protocol) 405 Method Not Allowed 응답 상태 코드는 요청 방법이 서버에서 알려져 있지만 대상 리소스에서 지원되지 않음을 나타냅니다.
생성 Url은 "localhost:5001/Create"
Create Get 메서드와 만 일치하는이고 양식은 HttpPost 요청을 보내므로 405 오류가 발생합니다.
1. asp-action="CreatePost"
양식 태그에 추가 할 수 있습니다.
2. 또는 CreatePost 작업에 동일한 경로 속성을 추가하십시오.
[HttpPost]
[Route("Create")]
public async Task<IActionResult> CreatePostAsync([Bind("Title", "Content")] Post post)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다