![](/img/trans.png)
[英]Why are my ASP.Net MVC4 WEBAPI ActionFilter being ignored at runtime?
[英]ASP.NET MVC: Why my custom ActionFilter changes my HTTP response code?
我开发了一个自定义操作过滤器,以便将它用于在 ASP.NET MVC 中记录我的 Web 服务的响应。 但是我不知道为什么当我将此操作过滤器添加到我的方法时,我的控制器的 HTTP 状态响应更改为 500 并返回消息: 500 Intenal Server Error
。 我将所有逻辑放在 try catch 块中,但问题仍然存在。
这是我的自定义 ActionFilter:
public class LogActionFilter : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
try
{
Log("OnActionExecuting", actionExecutedContext);
}
catch (Exception)
{
}
}
private void Log(string methodName, HttpActionExecutedContext context)
{
try
{
string resopnseBody = getBodyFromResponse(context);
HttpResponseMessage response = context.Response;
var headers = response.Headers;
var content = response.Content;
var actionName = response.ToString();
var message = "";
message = String.Format("response:{0}", resopnseBody);
Debug.WriteLine(message, "");
}
catch (Exception e)
{
}
}
private string getBodyFromResponse(HttpActionExecutedContext context)
{
string data;
using (var stream = context.Response.Content.ReadAsStreamAsync().Result)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;
}
return data;
}
}
更新:进一步调查我的代码,我发现调用getBodyFromResponse
会导致此错误。 我自己怀疑我会尝试读取流.Result
两次但是因为我复制了它! 来自其他地方的这段代码我不清楚它的逻辑。
Update2:这是我的控制器中的示例方法:
[LogActionFilter]
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> Test()
{
return Ok(new WebServiceResult { responseCode = 0, responseMessage = null });
}
更新 3:更换
resopnseBody = getBodyFromResponse(context);
下线修复了问题,但我不知道为什么!
resopnseBody = context.Response.Content.ReadAsStringAsync().Result;
我通过从 getBodyFromResponseAsync 中删除一些行来运行它
private string getBodyFromResponseAsync(HttpActionExecutedContext context)
{
return context.Response.Content.ReadAsStringAsync().Result;
}
我希望结果是你需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.