OWIN OAuthAuthorizationServerProvider自定义错误响应

时间:2016-05-25 13:12:33

标签: c# json oauth owin

对于当前的WebAPI,我使用OAuthAuthorizationServerProvider的自定义实现。

如果登录失败,我需要返回JSON响应。此响应是一个包含锁定时间的简单ViewModel,如果有的话。

然而,我无法发送回复。它要么以25个字符(?)被截断,要么以转义的C#string"\"lockout": 2"等方式发送。)

这是我到目前为止所尝试的:

context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(JsonConvert.SerializeObject(authResult));

1 个答案:

答案 0 :(得分:1)

通过将内容长度存储在Request上下文(暂时)来解决它。

context.Request.Set("Content-Length", json.Length.ToString());

然后在Startup.cs中获取它

if (c.Request.Environment.ContainsKey("Content-Length"))
{
    c.Response.ContentLength = Convert.ToInt64(c.Request.Environment["Content-Length"]);
    c.Response.ContentType = "application/json; charset=utf-8";
    c.Response.StatusCode = (int)HttpStatusCode.Unauthorized;  
}  
相关问题