如何自定义oauthauthorizationserverprovider错误信息?
如何 自定义 错误信息
2023-09-11 14:19:21 时间
We are using the OAuthAuthorizationServerProvider
class to do authorization in our ASP.NET Web Api app.
If the provided username and password is invalid in GrantResourceOwnerCredentials
, the call
context.SetError( "invalid_grant", "The user name or password is incorrect." );
Produces the following Json result:
{
"error": "invalid_grant",
"error_description": "The user name or password is incorrect."
}
Is there any way to customize this error result?
I would like to make it consistent with default error message format used in other parts of the API:
{
"message": "Some error occurred."
}
Is this possible to achieve with the OAuthAuthorizationServerProvider
?
2016年10月12日24分24秒
This is how I did it.
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);
2016年10月11日24分24秒
+1 for Dasun's answer. Here is how I extended it a bit further.
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);
}
}
The .ToJsonString() is another extension method that uses the Newtonsoft.Json library.
public static string ToJsonString(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
Usage:
context.SetCustomError("something went wrong");
相关文章
- 如何用软件测试来提高软件质量
- Unity关闭shader中的光照模型以及如何自定义光照模型
- Allegro如何添加平衡铜操作指导
- 如何编写和使用自定义的 Shell 函数和函数库
- Linux有问必答:如何在curl中设置自定义的HTTP头
- JAVA-- 在Java8 Parallel Stream中如何自定义线程池?
- Zeppelin如何进行安全及自定义主页设置?
- VS2010中如何实现自定义MFC控件
- 如何查看某个tag被打的时间?
- ubuntu18.04下如何开机自动执行自定义脚本?
- 【测试的艺术】测试用例质量如何衡量
- 【快应用】权限弹框理由描述如何自定义
- 【AGC】集成华为AGC应用内消息如何实现自定义样式
- 《嵌入式Linux与物联网软件开发——C语言内核深度解析》一1.5 C语言如何操作内存
- 如何在Vue项目中使用vw实现移动端适配(转)
- 什么是 ChatGPT 以及如何使用它进行教学?提示与技巧
- Nvidia GPU 入门教程之 04 如何在 Ubuntu 上安装 Anaconda Python 发行版
- SwiftUI SQLite教程之了解如何在 SwiftUI 中使用 SQLite 数据库并执行 CRUD 操作(教程含源码)
- 如何使用在 10 分钟内构建您的 Flutter 新闻应用程序而无需编码(Nowa 教程)
- vscod如何自定义 python虚拟环境
- 如何实现自定义单选样式改变颜色
- nuxt中vuex如何模块化分
- 浅析loader和plugin的本质、如何编写自定义的同步和异步的Loader、如何编写自定义的plugin及整个编译生命周期钩子
- uni-app知识点:禁止页面返回及如何实现自定义返回逻辑、实现再次返回退出应用时不退出应用而是在后台运行、uni-app ios滑动时卡顿不流畅问题解决方案
- 浅析如何自定义Java异常类且修改返回http状态码及解决状态码始终是200的问题和303状态码理解
- 微信公众号如何更新自定义菜单
- MDF文件损坏,如何恢复?(未解决)
- iOS开发 - 友盟分享(自定义分享)如何让新浪分享显示蓝色文字,其他平台内容不显示链接
- vue3:如何去挂载全局的变量和方法