Mar*_*cze 11 c# asp.net oauth asp.net-web-api
我们正在使用OAuthAuthorizationServerProvider
该类在我们的ASP.NET Web Api应用程序中进行授权.
如果提供的用户名和密码无效GrantResourceOwnerCredentials
,则通话
context.SetError( "invalid_grant", "The user name or password is incorrect." );
Run Code Online (Sandbox Code Playgroud)
产生以下Json结果:
{
"error": "invalid_grant",
"error_description": "The user name or password is incorrect."
}
Run Code Online (Sandbox Code Playgroud)
有没有办法自定义此错误结果?
我想使其与API的其他部分中使用的默认错误消息格式一致:
{
"message": "Some error occurred."
}
Run Code Online (Sandbox Code Playgroud)
这有可能实现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);
Run Code Online (Sandbox Code Playgroud)
给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);
}
}
Run Code Online (Sandbox Code Playgroud)
.ToJsonString()是另一个使用Newtonsoft.Json库的扩展方法.
public static string ToJsonString(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
Run Code Online (Sandbox Code Playgroud)
用法:
context.SetCustomError("something went wrong");
Run Code Online (Sandbox Code Playgroud)