亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何從 .NET CORE API 返回警告消息

我如何從 .NET CORE API 返回警告消息

C#
楊魅力 2023-09-16 14:58:55
我在客戶端使用 Angular。我在服務器端使用 .NET CORE WEB API,并使用 SQL Server 作為數據庫。我的 WEB API 有層次。業務邏輯層為我執行數據庫 dml 操作,并且我能夠執行 get 和 post http 客戶端操作。但我必須檢查業務邏輯層中的數據,如果數據格式錯誤,我想在客戶端上顯示錯誤,例如“此電話號碼格式錯誤。請輸入正確的格式”。我正確執行了 DML(INSERT、SELECT)操作。我需要返回錯誤消息的幫助,并且我想向用戶顯示此錯誤消息。這是 .NET Core Web API PersonController.cs    [Route("api/[controller]")]    [ApiController]    [EnableCors(origins: "http://example.com", headers: "*", methods: "*")]    public class PersonController : ControllerBase    {        FihristBLL bll = new FihristBLL();        // GET: api/Person        [HttpGet]        public List<Person> Get()        {            return bll.GetNumbers();        }        // POST: api/Person        [HttpPost]        public void Post([FromBody] Person person)        {            bll.AddNumber(person);        }    }}這是執行數據庫操作的業務邏輯層    public class FihristBLL    {        public void AddNumber(Person person)        {                if (person.PhoneNumber.Substring(0, 1) != "5" || 0 % Convert.ToInt64(person.PhoneNumber) != 0)                {                // WRONG FORMAT                }                else                {                    // CORRECT FORMAT                          FihristDAL db = new FihristDAL();                    SqlConnection conn = db.OpenConnection();                    string command = "INSERT INTO Persons (PhoneNumber,FirstName,LastName) VALUES (@phoneNumber,@firstName,@lastName)";                    SqlCommand sqlCommand = db.CreateConnection(command);                    sqlCommand.Parameters.AddWithValue("@phoneNumber", person.PhoneNumber);                    sqlCommand.Parameters.AddWithValue("@firstName", person.FirstName);                    sqlCommand.Parameters.AddWithValue("@lastName", person.LastName);                    sqlCommand.ExecuteNonQuery();                    conn.Close();                }             }    }}操作完美,工作正常。但我需要返回錯誤消息,例如“您剛剛輸入了格式錯誤的電話號碼”。并在 Angular 上顯示此消息。
查看完整描述

4 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

快速響應是拋出一個ArgumentException帶有驗證錯誤描述的錯誤,在控制器級別捕獲它并將其映射到錯誤響應中,并以異常消息作為內容:


var validPhoneNumber = //your validation logic stuff

if (!validPhoneNumber ){

? ?throw new ArgumentException("Invalid phone number");

}


[HttpPost]

public IActionResult Post([FromBody] Person person)

{

? ? try{

? ? ? bll.AddNumber(person);

? ? }catch(ArgumentException argumentEx){

? ? ? ?return BadRequest(new {Message = argumentEx.Message});

? ? }

? ? // A better approach would be to return the created resource at this point

? ? return this.NoContent();

}

在角度方面,錯誤有效負載應該在 的實例中可用HttpResponseError。


查看完整回答
反對 回復 2023-09-16
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

您可以使用該模型并將其返回。


public class Response<T>

{

        public Response(bool defalut = false)

        {

            IsSuccess = defalut;

            Message = "";

        }


        public Response(string message)

        {

            IsSuccess = false;

            Message = message;

        }


        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public T Data { get; set; }

}


查看完整回答
反對 回復 2023-09-16
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

我會嘗試將驗證邏輯封裝在一個對象中,序列化該對象并將其發送到 Angular,然后在 Angular 中檢查一切是否正常,然后繼續,否則顯示一些錯誤消息。



查看完整回答
反對 回復 2023-09-16
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

當格式錯誤時,您可以拋出異常并簡單地返回HttpResponseMessage?,如下所示:

[HttpPost]

public void Post([FromBody] Person person)

{

? ? try?

? ? {

? ? ? ? bll.AddNumber(person);

? ? }

? ? // Replace with own exception

? ? catch (FormatException e)

? ? {

? ? ? ? return new HttpResponseMessage(HttpStatusCode.BadRequest)

? ? ? ? {

? ? ? ? ? ? ReasonPhrase = "Phone number is not correctly formatted"

? ? ? ? };

? ? }


? ? return new HttpResponseMessage(HttpStatusCode.OK);

}


查看完整回答
反對 回復 2023-09-16
  • 4 回答
  • 0 關注
  • 211 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號