Request.Cookies [" cookieName"]在Web服务方法中为null

时间:2017-07-07 07:20:44

标签: c# asp.net web-services cookies

这就是我在我的代码中保存cookie的方式,这是一种Web服务方法。我试图改变cookie过期时间,但它仍然不适合我。 Context.Response编写cookie或Context.Request来阅读它是否有任何问题?

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}

在下一页检索此Cookie

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}

但我的对象getCookie始终是null

2 个答案:

答案 0 :(得分:0)

Rajesh,表单仅存在于Web应用程序中。如果您使用普通网络API创建服务,则不会向您的服务客户端提供任何表单。

要创建Cookie:     var resp = new HttpResponseMessage();

var cookie = new CookieHeaderValue("session-id", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";

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

使用cookie:

CookieHeaderValue cookie = Request.Headers.GetCookies("session-id")

答案 1 :(得分:0)

我通过将Cookie存储为

来获得此功能
HttpContext.Current.Response.Cookies.Add(formCookie);

并将其视为

var getCookie=HttpContext.Current.Request.Cookies["UserData"];