ASP.NET MVC:为什么我的自定义ActionFilter更改我的HTTP响应代码?

问题描述 投票:0回答:1

我已经开发了一个自定义操作过滤器,以便将其用于在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;
c# asp.net-mvc action-filter actionfilterattribute custom-action-filter
1个回答
0
投票

我通过从getBodyFromResponseAsync中删除一些行来运行它>

private string getBodyFromResponseAsync(HttpActionExecutedContext context)
{
    return context.Response.Content.ReadAsStringAsync().Result;
}

我希望结果就是您所需要的。

© www.soinside.com 2019 - 2024. All rights reserved.