4 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個贊
快速響應(yīng)是拋出一個ArgumentException帶有驗(yàn)證錯誤描述的錯誤,在控制器級別捕獲它并將其映射到錯誤響應(yīng)中,并以異常消息作為內(nèi)容:
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();
}
在角度方面,錯誤有效負(fù)載應(yīng)該在 的實(shí)例中可用HttpResponseError。

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超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; }
}

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個贊
我會嘗試將驗(yàn)證邏輯封裝在一個對象中,序列化該對象并將其發(fā)送到 Angular,然后在 Angular 中檢查一切是否正常,然后繼續(xù),否則顯示一些錯誤消息。

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個贊
當(dāng)格式錯誤時,您可以拋出異常并簡單地返回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);
}
- 4 回答
- 0 關(guān)注
- 208 瀏覽
添加回答
舉報