我是ASP.NET Core3.1的新手,没有MVC的背景。我只是从Web转到ASP.NET核心。我问了其他地方,我得到了关于我的代码的以下评论。这段代码对我来说很好,但我不知道如何通过提供的反馈来改进它。
我想知道如何清理这些代码,并根据下面的代码编写更优化的代码。我希望有代码的例子。
其实有点小问题。没有必要显式地打开或关闭连接(Dapper将打开它),即使在最终无法执行的情况下,使用也会释放连接。另一个bug捕获(异常ex){抛出ex;}抛出一个具有不同堆栈跟踪的新异常。这比没有抓到更糟。若要在例如日志记录之后重新抛出原始异常,请使用抛出;,没有异常对象。
Editor注释:引语中写着“bug”或"bug",但是引用的东西实际上并不是bug。它们是删除冗余代码或更改异常语义的副作用的建议。
NewsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookListRazor.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Dapper;
using Microsoft.Data.SqlClient;
using System.Data;
using BookListRazor.Data;
namespace BookListRazor.Controllers
{
// [Route("api/News")]
//[Route("api/News/[action]")]
[ApiController]
public class NewsController : Controller
{
//for EF
private readonly ApplicationDbContext _db;
//For Dapper
private readonly SqlConnectionConfiguration _configuration;
public NewsController(ApplicationDbContext db, SqlConnectionConfiguration configuration)
{
_db = db;
_configuration = configuration;
}
//get all news
[HttpGet]
[Route("api/news/GetAll")]
public async Task GetAll()
{
//fetch data using EF
// return Json(new { data = await _db.News.OrderByDescending(x => x.NewsDate).ToListAsync() });
//Fetch data using Dapper
IEnumerable newslist;
using (var conn = new SqlConnection(_configuration.Value))
{
string query = "select * FROM News";
conn.Open();
try
{
newslist = await conn.QueryAsync(query, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return Json(new { data = newslist });
}
}
}在剃须刀/cshtml中:
$(document).ready(function () {
$.ajax({
url: "api/news/getallnews/1",
type: "GET",
dataType: "json",
success: function (response) {
var len = response.data.length;
var table = $("<table><tr><th>Details</th></tr>");
for (var i = 0; i < len; i++) {
//console.log("i "+i);
table.append("<tr><td>Title:</td><td>" + response.data[i].newsHeading + "</td></tr>");
}
table.append("</table>");
$("#news").html(table);
}
});
});以及:
//get all news
[HttpGet]
[Route("api/news/GetAllData")]
public async Task GetAllData()
{
using (SqlConnection connection = new SqlConnection(_configuration.Value))
{
var param = new DynamicParameters();
// param.Add("@prodtype", prodtype);
//return connection.QueryFirst(" select * FROM News");
string query = "select * FROM News";
IEnumerable newslist;
newslist = await connection.QueryAsync(query, commandType: CommandType.Text);
return Json(new { data = newslist });
}
}发布于 2020-07-02 11:05:36
老实说,在try/catch/finally中,您已经得到的反馈似乎非常有效;重新抛出您直接捕获的异常是没有价值的;如果这是在某种处理之后,那么throw; (没有异常实例)是一个很好的方法,可以在不损坏原始异常的情况下重新抛出它,但在您的示例中,整个过程是多余的,所以--完全丢失GetAll,让using担心其余的事情。此外,还不如将查询保留为“内联”,并且使用AsList()可以清楚地表明,我们现在而不是以后实现对象(这可能会导致延迟执行的问题)。这与默认设置相同,因此这里的AsList()不会改变行为--只会让读者更清楚地看到:
using (var conn = new SqlConnection(_configuration.Value))
{
var newslist = (await conn.QueryAsync("select * FROM News")).AsList();
return Json(new { data = newslist });
}在GetAllData中你不使用param,所以修剪-它变成.哈,一样的!
using (SqlConnection connection = new SqlConnection(_configuration.Value))
{
var newslist = (await connection.QueryAsync("select * FROM News")).AsList();
return Json(new { data = newslist });
}最后,在jQuery回调中,注意XSS --关于一个非常类似的示例,请参见这篇文章写在所以。问题是,要明确地说,response.data[i].newsHeading可能是恶意的-例如,它可能包含</code>。</div>
发布于 2020-07-02 15:37:23
其他次要问题:
整理一下你的usings和把它们移到你的内部namespace。还可以考虑使用StyleCop,这说明了这一点。
为什么这些
private readonly ApplicationDbContext _db;
private readonly SqlConnectionConfiguration _configuration;有下划线吗?通常,这是Python的约定。如果你担心在这里消除歧义:
public NewsController(ApplicationDbContext db, SqlConnectionConfiguration configuration)
{
_db = db;
_configuration = configuration;
}然后,您可以简单地在目的地前缀加上this.。
应删除整个区块:
catch (Exception ex)
{
throw ex;
}你仍然可以保留你的finally。但是,您也不应该在其中包含finally,因为with中已经有了conn。您的显式close重复了IDisposable强加于该连接的close。
IEnumerable newslist;
newslist = await connection.QueryAsync(query, commandType: CommandType.Text);不需要是两个单独的语句;您可以在第一个语句上执行赋值。
https://codereview.stackexchange.com/questions/244869
复制相似问题