gpt4 book ai didi

c# - 从 OWIN 中间件返回异常

转载 作者:行者123 更新时间:2023-11-30 16:01:42 35 4
gpt4 key购买 nike

我有一个 OWIN 中间件类来根据一些自定义 token 进行一些身份验证。一切正常。但是我想向客户端返回一个有用的错误响应。我的理由是,如果客户要求“application/json”响应并且他们期望序列化对象,那么这就是他们应该得到的,即使它是 401 状态代码。

这是我的中间件的调用部分:

    public override async Task Invoke(IOwinContext context)
{
try
{
this.DoAuthorization(context);
await this.Next.Invoke(context);
}
catch (UnauthorizedAccessException ex)
{
this.GenerateErrorResult(context, HttpStatusCode.Unauthorized, this.ExceptionToString(ex));
}
catch (Exception ex)
{
this.GenerateErrorResult(context, HttpStatusCode.InternalServerError, this.ExceptionToString(ex));
}
}

private void GenerateErrorResult(IOwinContext context, HttpStatusCode code, string errorMessage)
{
var result = new Result { Status = Result.EStatus.Error, ErrorText = errorMessage };

context.Response.StatusCode = (int)code;
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(result));
}

这一切都很好,但是:

  • 这是“正确”的方式吗?
  • 如果客户端要求'application/xml'怎么办,这显然是 Web API 能够支持的

是否有更好的方法来返回按客户期望序列化的自定义响应对象(在我的例子中为“结果”)?

最佳答案

这似乎可行,首先使用一个额外的 OwinMiddleware:

   public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (UnauthorizedAccessException ex)
{
var result = new Result { Status = Result.EStatus.Error, ErrorText = ExceptionToString(ex) };

this.ReturnFormattedResult(result, HttpStatusCode.Unauthorized, context);
}
catch (Exception ex)
{
var result = new Result { Status = Result.EStatus.Error, ErrorText = ExceptionToString(ex) };

this.ReturnFormattedResult(result, HttpStatusCode.InternalServerError, context);
}
}

private void ReturnFormattedResult(Result result, HttpStatusCode code, IOwinContext context)
{
// what should our response be?
var mediaType = context.Request.MediaType ?? context.Request.ContentType;

// use the accept header (unless it is empty or '*/*' in which case use the content-type
if (!string.IsNullOrEmpty(context.Request.Accept) && !context.Request.Accept.Contains("*/*"))
{
mediaType = context.Request.Accept;
}

// find a formatter for this media type, if no match then use the first one
var formatter = this.config.Formatters.FindWriter(typeof(Result), new MediaTypeHeaderValue(mediaType));
if (formatter == null)
{
formatter = this.config.Formatters.First();
mediaType = formatter.SupportedMediaTypes.First().MediaType;
}

context.Response.StatusCode = (int)code;
context.Response.ContentType = mediaType;
formatter.WriteToStreamAsync(typeof(Result), result, context.Response.Body, null, null).Wait();
}

关于c# - 从 OWIN 中间件返回异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38437640/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com