【发布时间】:2020-06-02 07:15:34
【问题描述】:
当 .Net Web API 返回 Badrequest("this is an example of Badrequest".) 时,我的中间件中的 IOwinContext 对象仅包含 context.Response.StatusCode 400 和 context.Response.ReasonPhrase 作为“错误请求”。我想要实际的错误消息,以便我可以在某处记录它。是否可以在不编写任何自定义类的情况下从IOwinContext 获取实际错误消息?
编辑: Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
ICoreLogger dv_logger = new CoreLogger();
app.Use<InvalidAuthenticationMiddleware>(dv_logger);
ConfigureOAuth(app);
//register log4net
XmlConfigurator.Configure();
// configure log4net variables
GlobalContext.Properties["processId"] = "dv_logger";
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//entity framework
DbContext.Intialize();
AuthContext.Intialize();
.....
}
中间件
public class InvalidAuthenticationMiddleware : OwinMiddleware
{
public override async Task Invoke(IOwinContext context)
{
var stream = context.Response.Body;
using (var buffer = new MemoryStream())
{
context.Response.Body = buffer;
await Next.Invoke(context);
buffer.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(buffer))
{
string responseBody = await reader.ReadToEndAsync();
if (context.Response.StatusCode == (int)HttpStatusCode.BadRequest)
{
var definition = new { Message = "" };
var error = JsonConvert.DeserializeAnonymousType(responseBody, definition);
Debug.WriteLine(error.Message);
}
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(stream);
}
}
}
}
控制器
public class LoginController : BaseController
{
[Route("")]
public IHttpActionResult Get(string email)
{
return BadRequest("this is an example of bad request!");
}
}
【问题讨论】:
-
ConfigureOAuth()是做什么的?你为什么不使用appBuilder.UseWebApi(config)而不是GlobalConfiguration.Configure()?您应该简化您的Startup.Configuration()并删除一些部分以缩小您的问题范围。 -
我们使用的是
appBuilder.UseWebApi(config),但我们的项目中也有一个 MVC 控制器。所以,我们不得不切换到GlobalConfiguration.Configure()。ConfigureOAuth设置 Owin 授权的属性。
标签: c# asp.net-web-api2 owin http-status-code-400 owin-middleware