简体   繁体   中英

HttpClient result from a WebAPI Request.CreateResponse (StatusCode, Message)

I have a WebAPI method that looks like this:

    public HttpResponseMessage Login([FromBody] LoginType form)
    {
        if (LoginFails(form.Email, form.Password)
             return Request.CreateErrorResponse(HttpStatusCode.OK, 
                            "Sorry your login failed");

        return this.Request.CreateResponse(HttpStatusCode.OK);
    }

I have an Client that looks like this:

        var sample = new LoginType()
        {
            login = "test",
            Password = "password"
        };

        var client = new HttpClient();
        client.BaseAddress = new Uri("www.example.com);
        client.DefaultRequestHeaders.Accept.Add(
               new MediaTypeWithQualityHeaderValue("application/json"));

        var result = client.PostAsJsonAsync("api/security/login", sample).Result;

QUESTION 1: Where in the result variable, I can read the message "Sorry your login failed" ??
QUESTION 2: When returning a CreateErrorResponse, does it make sense to return HttpStatusCode.OK ??

Q1: From Response.Content . If content type is application/json, you can do:

response.Content.ReadAsStringAsync().Result;

Q2: I would return HttpStatusCode.Unauthorized if the login failed.

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