2016-03-04 12 views
1

自定義HTTP響應代碼當使用ASP.NET的WebAPI 2 OAuthAuthorizationServerProvider一個可以的重寫方法中做定製憑證驗證:發送從GrantResourceOwnerCredentials

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 

在情況下的誤差(DB連接錯誤,例如)發生在執行此方法期間,我想向請求者返回至少500個內部服務器錯誤。我似乎無法通過context.Response.StatusCode = 500;設置自定義狀態代碼有沒有一種方法來控制此方法的響應代碼?

回答

1

Based on Greg P's original answer,有一些修改

第一步:創建一個類將作爲您的中間件

using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, System.Object>, 
System.Threading.Tasks.Task>; 

命名空間SignOnAPI.Middleware.ResponseMiddleware {

public class ResponseMiddleware 
{ 
    AppFunc _next; 
    ResponseMiddlewareOptions _options; 

    public ResponseMiddleware(AppFunc nex, ResponseMiddlewareOptions options) 
    { 
     _next = next; 
    } 

    public async Task Invoke(IDictionary<string, object> environment) 
    { 
     var context = new OwinContext(environment); 

     await _next(environment); 

     if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey("Change_Status_Code")) 
     { 
      //read the status code sent in the response 
      var headerValues = context.Response.Headers.GetValues("Change_Status_Code"); 

      //replace the original status code with the new one 
      context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault()); 

      //remove the unnecessary header flag 
      context.Response.Headers.Remove("Change_Status_Code"); 
     } 
    } 
} 

第二步:創建擴展類(可以省略)。

此步驟是可選的,可以進行修改以接受可傳遞給中間件的選項。

public static class ResponseMiddlewareExtensions 
{ 
    //method name that will be used in the startup class, add additional parameter to accept middleware options if necessary 
    public static void UseResponseMiddleware(this IAppBuilder app) 
    { 
     app.Use<ResponseMiddleware>(); 
    } 
} 

第三步:在您的OAuthAuthorizationServerProvider實現修改GrantResourceOwnerCredentials方法

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 

     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 

     if (<database connection failed) 
     { 
      //first reject the context, to signify that the client is not valid 
      context.Rejected(); 

      //set the error message 
      context.SetError("invalid_username_or_password", "Invalid userName or password"); 

      //add a new key in the header along with the statusCode you'd like to return 
      context.Response.Headers.Add("Change_Status_Code", new[] { ((int)HttpStatusCode.InternalServerError).ToString() }); 
      return; 
     } 
    } 

第四步:在啓動類使用此中間件

public void Configuration(IAppBuilder app) 
{ 
    app.UseResponseMiddleware(); 

    //configure the authentication server provider 
    ConfigureOAuth(app); 

    //rest of your code goes here.... 
}