简体   繁体   中英

ASP.NET MVC: Why my custom ActionFilter changes my HTTP response code?

I've developed a custom action filter in order to use it for logging response of my web-service in ASP.NET MVC. However I don't know why when I add this action filter to my method, HTTP status response of my controller changes to 500 and it returns the message: 500 Intenal Server Error . I put all logic inside try catch block but still problem persists.

Here is my custom 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;
    }
}

Update: Furthur investigating my code I found that calling getBodyFromResponse leads to this error. I myself suspect to part which I will try to read stream .Result twice however since I copied! this code from elsewhere I don't understand its logic clearly.

Update2: Here is a sample method in my controller:

[LogActionFilter]
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> Test()
{
     return Ok(new WebServiceResult { responseCode = 0, responseMessage = null });
}

Update 3: replacing

resopnseBody = getBodyFromResponse(context);

with below line fixed issue but I don't know why!

resopnseBody = context.Response.Content.ReadAsStringAsync().Result;

I got it to run by removing some lines from getBodyFromResponseAsync

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

I hope the result is what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM