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

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吗?

Das*_*sun 8

这就是我做到的.

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)

  • 这在web api 2上对我不起作用.由于您提到的内部错误,响应不合适json. (3认同)

use*_*333 5

给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)

  • 使用最新版本的web api 2时,这对我不起作用. (5认同)