' ObjectContent`1'类型无法序列化内容类型的响应主体' application / json;

时间:2017-02-27 05:41:50

标签: json asp.net-web-api asp.net-mvc-5

您好我的web api控制器中有注销页面。我能够打网址,我正在清除cookie,但我得到的回应是' ObjectContent`1'类型无法序列化内容类型的响应主体' application / json; 以下是我的代码。

 [HttpGet]
        [Route("~/api/auth/logout")]
        //Log out code
        public HttpResponseMessage Get()
        {

            var currentCookie = Request.Headers.GetCookies("session").FirstOrDefault();
            var response = Request.CreateResponse(HttpStatusCode.OK);
            if (response!= null)
            {
                var cookie = new CookieHeaderValue("session", "")
                {
                    Expires = DateTimeOffset.Now.AddDays(-1),
                    Domain = currentCookie.Domain,
                    Path = currentCookie.Path
                };
                response.Headers.AddCookies(new[] { cookie });
                return Request.CreateResponse(HttpStatusCode.OK, response);
            }
            else
            {
            return response
            }
        }

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

我创建了如下过滤器。

public class Action1DebugActionWebApiFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var response = actionExecutedContext.Response;
            var request = actionExecutedContext.Request;

            var currentCookie = request.Headers.GetCookies("session").FirstOrDefault();
            if (currentCookie != null)
            {
                var cookie = new CookieHeaderValue("session", "")
                {
                    Expires = DateTimeOffset.Now.AddDays(-1),
                    Domain = currentCookie.Domain,
                    Path = currentCookie.Path
                };

                response.Headers.AddCookies(new[] { cookie });
            }

            base.OnActionExecuted(actionExecutedContext);
        }
    }

在操作方法中修饰过滤器,如下所示。

[Route("~/api/auth/logout")]
[Action1DebugActionWebApiFilter]
public HttpResponseMessage Get()
{
    var message = string.Format("Logged Out");
    HttpError msg = new HttpError(message);
    return Request.CreateResponse(HttpStatusCode.OK, msg);
}

它开始工作了。