Возврат файла cookie вместе с объектом из веб-API .NET

Я использую .NET Web API и хочу отправить вновь созданный файл cookie вместе со строкой, сгенерированной в Web API.

Код C #:

public Tuple<HttpResponseMessage, string> CookieMessage()
{
        string result = "Cookie Created Successfully !";

        CookieHeaderValue serverCookie = new CookieHeaderValue("", "");

        serverCookie = new CookieHeaderValue
                                ("IEM", "Success");
        serverCookie.Expires = DateTimeOffset.Now.AddMinutes(15);
        serverCookie.Domain = Request.RequestUri.Host;
        serverCookie.Path = "/";


    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

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

    return Tuple.Create(response, result);

}

Как я мог отправить ответ "Cookie Created Successfully !" вместе с файлом cookie serverCookie

Пожалуйста, помогите мне отправить эти два в одном ответе клиенту. Я получаю внутреннюю ошибку сервера 500

В ответе я видел следующее сообщение

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException" ,"StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'SeparatorsArray' on 'System.Version'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException" ,"StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer , Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract & memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter .Serialize(JsonWriter jsonWriter, Object value)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal (JsonWriter jsonWriter, Object value)\r\n at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter , Object value)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.

b__c()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Common Language Runtime detected an invalid program.","ExceptionType":"System.InvalidProgramException","StackTrace":" at GetSeparatorsArray (Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}


person Community    schedule 15.06.2016    source источник
comment
Вы запускали его под отладчиком, чтобы увидеть, какое исключение выбрасывается?   -  person fahadash    schedule 15.06.2016
comment
@fahadash В веб-API возвращает без исключения. Я приклеил ответ. Пожалуйста, проверьте это один раз.   -  person    schedule 15.06.2016


Ответы (1)


Вы возвращаете неподдерживаемый тип. Я уверен, что фреймворк никогда не сможет сериализовать Tuple<HttpResponseMessage, string>. Если вы хотите изменить заголовки ответов, вам нужно вернуть только HttpResponseMessage.

Это должно работать так, как вы ожидаете:

public HttpResponseMessage CookieMessage()
{
    var response = Request.CreateResponse<string>(
        HttpStatusCode.OK,
        "Cookie Created Successfully !"
    );

    var cookie = new CookieHeaderValue("IEM", "Success");
    cookie.Expires = DateTimeOffset.Now.AddMinutes(15);
    cookie.Domain = Request.RequestUri.Host;
    cookie.Path = "/";

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

    return response;
}
person Federico Dipuma    schedule 15.06.2016