如何自定义OAuthAuthorizationServerProvider的错误消息?

我们使用OAuthAuthorizationServerProvider类在我们的ASP.NET Web Api应用程序中进行授权。

如果在GrantResourceOwnerCredentials提供的用户名和密码无效,则调用

 context.SetError( "invalid_grant", "The user name or password is incorrect." ); 

生成以下Json结果:

 { "error": "invalid_grant", "error_description": "The user name or password is incorrect." } 

有没有办法自定义此错误结果?
我想使它与API的其他部分中使用的默认错误消息格式一致:

 { "message": "Some error occurred." } 

这是否可以通过OAuthAuthorizationServerProvider实现?

这就是我做到的。

 string jsonString = "{\"message\": \"Some error occurred.\"}"; // This is just a work around to overcome an unknown internal bug. // In future releases of Owin, you may remove this. context.SetError(new string(' ',jsonString.Length-12)); context.Response.StatusCode = 400; context.Response.Write(jsonString); 

给Dasun的答案+1。 这是我如何进一步扩展它。

 public class ErrorMessage { public ErrorMessage(string message) { Message = message; } public string Message { get; private set; } } public static class ContextHelper { public static void SetCustomError(this OAuthGrantResourceOwnerCredentialsContext context, string errorMessage) { var json = new ErrorMessage(errorMessage).ToJsonString(); context.SetError(json); context.Response.Write(json); } } 

.ToJsonString()是另一个使用Newtonsoft.Json库的扩展方法。

 public static string ToJsonString(this object obj) { return JsonConvert.SerializeObject(obj); } 

用法:

 context.SetCustomError("something went wrong");