Imports System.Net
Imports System.Web.Http
Imports System.Net.Http
Imports Newtonsoft.Json
Imports System.Web.Http.Filters
''' <summary>
''' 登入驗證錯誤自訂訊息
''' </summary>
''' <remarks> </remarks>
Public Class TestAuthorizeAttribute
Inherits AuthorizeAttribute
Protected Overrides Sub HandleUnauthorizedRequest(actionContext As Controllers.HttpActionContext)
MyBase.HandleUnauthorizedRequest(actionContext)
actionContext.Response.Content = New StringContent(JsonConvert.SerializeObject(New Dictionary(Of String, String) From {{"result", "-1"}}, Formatting.Indented))
Select Case actionContext.Response.StatusCode
Case 401
Dim dicError As Dictionary(Of String, String) =
New Dictionary(Of String, String) From {
{"result", "-1"},
{"msg", "Login First"}
}
actionContext.Response.Content = New StringContent(JsonConvert.SerializeObject(dicError, Formatting.Indented))
Case Else
actionContext.Response.Content = New StringContent(JsonConvert.SerializeObject(New Dictionary(Of String, String) From {{"result", "-1"}}, Formatting.Indented))
End Select
End Sub
End Class
''' <summary>
''' 例外錯誤自訂訊息
''' </summary>
''' <remarks></remarks>
Public Class TestExceptionFilterAttribute
Inherits ExceptionFilterAttribute
Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
MyBase.OnException(actionExecutedContext)
Dim resp As New HttpResponseMessage
resp.Content = New StringContent(JsonConvert.SerializeObject(New Dictionary(Of String, String) From {{"result", "-1"}, {"msg", "Custom Exception"}}, Formatting.Indented))
actionExecutedContext.Response = resp
End Sub
End Class
''' <summary>
''' 參數格式錯誤自訂訊息
''' </summary>
''' <remarks></remarks>
Public Class TestActionFilterAttribute
Inherits ActionFilterAttribute
Public Overrides Sub OnActionExecuting(actionContext As Controllers.HttpActionContext)
MyBase.OnActionExecuting(actionContext)
If Not actionContext.ModelState.IsValid Then
Dim resp As New HttpResponseMessage
resp.Content = New StringContent(JsonConvert.SerializeObject(New Dictionary(Of String, String) From {{"result", "-1"}, {"msg", "Format Error"}}, Formatting.Indented))
actionContext.Response = resp
End If
End Sub
End Class
Public Class ValuesController
Inherits ApiController
' GET api/values
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
' GET api/values/5
Public Function GetValue(ByVal id As Integer) As String
Return "value"
End Function
' POST api/values
Public Sub PostValue( ByVal value As String)
End Sub
' PUT api/values/5
Public Sub PutValue(ByVal id As Integer, ByVal value As String)
End Sub
' DELETE api/values/5
Public Sub DeleteValue(ByVal id As Integer)
End Sub
End Class
實做登入機制
http://demo.tc/Post/534
留言