locked
Writing cookie from web api RRS feed

  • Question

  • User-656906411 posted

    Hi.

    I can't seem to write a cookie in a web api POST request.

    public HttpResponseMessage Post(HttpRequestMessage JSONData)
            {
                dynamic data = JObject.Parse(JSONData.Content.ReadAsStringAsync().Result);
    
                var resp = new HttpResponseMessage();
                NameValueCollection cookieValues = new NameValueCollection();
    
                foreach (JToken cookieItem in data.SelectToken("cookieItems"))
                {
                    cookieValues.Add(cookieItem["name"].ToString(), cookieItem["value"].ToString());                
                }
    
    
                var cookie = new CookieHeaderValue((string)data.cookieName, cookieValues);
                //cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";
    
                resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                resp.Content = new StringContent("{}");
                return resp;
            }

    My jquery code for calling the api:

    function callRestAPI(controller, data, method, successCallback) {
    
        $.ajax({
            url: restAPIurl + controller,
            data: JSON.stringify(data),
            contentType: 'application/json',
            dataType: "json",
            method: method,
            success: function (data, textStatus, jqXHR) {            
                successCallback(data, textStatus, jqXHR);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('An error has occured.\n\n' + JSON.parse(jqXHR.responseText).error);
            }
        });
    }
    
    
    var jsonData = {
        "cookieName": "login",
        "cookieItems": [
            {
                "name": "userID",
                "value": data.userID
            },
            {
                "name": "authToken",
                "value": data.authToken
            }
        ]
    };
    
    callRestAPI('cookie', jsonData, "POST", function (data, textStatus, jqXHR) {
        alert('finished');
    });

    If i set the web api method as a GET and just browse to it, then it works.

    but as it is now, there is not set-cookie header in the response

    Sunday, March 31, 2019 1:09 AM

All replies

  • User283571144 posted

    Hi SectionOne,

    According to your description, I have written a test demo on my side, it shows the response header in the F12 develop tool as below:

    I guess you use chrome to test the application, as far as I know the chrome has spcial security setting which doesn't show the response header with localhost.

    I suggest you could try to use IE or edge to test, it will work well.

    More details about my test demo codes, you could refer to below codes:

    Client-side script:

    <script>
        var jsonData = {
            "cookieName": "login",
            "cookieItems": [
                {
                    "name": "userID",
                    "value": "data.userID"
                },
                {
                    "name": "authToken",
                    "value": "data.authToken"
                }
            ]
        };
        $(function () {
            callRestAPI('cookie', jsonData, "POST", function (data, textStatus, jqXHR) {
                alert('finished');
            });
        });
    
    
        function callRestAPI(controller, data, method, successCallback) {
    
        $.ajax({
            url: "http://localhost:65099/api/values",
            data: JSON.stringify(data),
            contentType: 'application/json',
            dataType: "json",
            method: method,
            success: function (data, textStatus, jqXHR) {
                successCallback(data, textStatus, jqXHR);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('An error has occured.\n\n' + JSON.parse(jqXHR.responseText).error);
            }
        });
    }
    </script>

    WebAPI Action:

            public HttpResponseMessage Post(HttpRequestMessage JSONData)
            {
                dynamic data = JObject.Parse(JSONData.Content.ReadAsStringAsync().Result);
    
                var resp = new HttpResponseMessage();
                NameValueCollection cookieValues = new NameValueCollection();
    
                foreach (JToken cookieItem in data.SelectToken("cookieItems"))
                {
                    cookieValues.Add(cookieItem["name"].ToString(), cookieItem["value"].ToString());
                }
    
    
                var cookie = new CookieHeaderValue((string)data.cookieName, cookieValues);
                //cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Domain = Request.RequestUri.Host;
    
                //cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";
    
                resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                resp.Content = new StringContent("{}");
                return resp;
            }

    Best Regards,

    Brando

    Monday, April 1, 2019 3:10 AM
  • User-656906411 posted

    Well, I've tested with FIrefox.

    I do see the set-cookies header in that browser, but the cookie is missing when i go to "Storage" in the developer toolbar,

    or when i do "document.cookie" in the console.

    And no, the cookie is not HttpOnly.

    I am running my site on a fake domain defined in my hosts.

    But that shouldn't matter..

    my rest api is on api.mydomain.com

    and i'm calling it from mydomain.com

    maybe that is part of the problem..

    Tuesday, April 2, 2019 3:26 PM
  • User-656906411 posted

    Ok, I "solved" it.

    I added an Application folder in IIS to my main site and called it "api".

    So instead of making requests to api.mydomain.com i'm now making them to mydomain.com/api

    And everything works.

    Still would like to know how to set it up with a subdomain..

    Tuesday, April 2, 2019 3:43 PM