iT邦幫忙

0

CreateErrorResponse 與 CreateResponse 有何差異

  • 分享至 

  • twitterImage

請問這兩個功能有何差異,感覺只是差在T value

public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message);

public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode, T value);

但如果我想傳的錯誤是一個類別或物件進去,CreateErrorResponse好像沒有,只能string message
請求失敗()
{
"code" : "400",
"message" : "自定"message",
"detail" : "自定detail",
"data" : "none"
}

因為發生錯誤 只需要錯誤訊息,但如果是正常回傳,是能回傳其他類別的
如果你用CreateErrorResponse 設HttpStatusCode.OK 回傳正常訊息
我想應該會被打吧 哈哈
然後 請你把有人回答的問題設下最佳解答
差在 Error
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-12-03 23:04:48

簡單說
一般/正常 HTTP Response 用 CreateResponse
異常 HTTP Response 用 CreateErrorResponse

CreateResponse

CreateResponse is a Helper method that performs content negotiation and creates a HttpResponseMessage with an instance of System.Net.Http.ObjectContent`1 as the content and OK as the status code if a formatter can be found. If no formatter is found, this method returns a response with status 406 NotAcceptable.

CreateErrorResponse

CreateErrorResponse also a Helper method that creates a HttpResponseMessage representing an error with an instance of System.Net.Http.ObjectContent`1 wrapping an HttpError for model state modelState. If no formatter is found, this method returns a response with status 406 NotAcceptable

When to Use:

Usually when your request would have successful response then you have to use CreateResponsewith http status code. on the other hand if your request encounters a server side exception its good to handle with CreateErrorResponse with relevant error code.

資料來源

我要發表回答

立即登入回答