在ASP.Net Core中,你可以使用多种方法来创建和存储网页文章。以下是一种基本的解决方法,包含代码示例:
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class ArticleDbContext : DbContext
{
public ArticleDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Articles { get; set; }
}
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
[ApiController]
[Route("api/[controller]")]
public class ArticlesController : ControllerBase
{
private readonly ArticleDbContext _context;
public ArticlesController(ArticleDbContext context)
{
_context = context;
}
[HttpGet]
public async Task>> GetArticles()
{
return await _context.Articles.ToListAsync();
}
[HttpPost]
public async Task> CreateArticle(Article article)
{
_context.Articles.Add(article);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetArticles), new { id = article.Id }, article);
}
}
POST /api/articles
Content-Type: application/json
{
"title": "Example Title",
"content": "Example Content"
}
使用GET请求获取所有文章:
GET /api/articles
以上代码示例演示了如何使用ASP.Net Core创建和存储网页文章。你可以根据实际需求进一步扩展和优化这个解决方案。