来自WebAPI Request.CreateResponse(StatusCode,Message)的HttpClient结果

时间:2013-10-18 20:05:03

标签: c# asp.net-web-api

我有一个WebAPI方法,如下所示:

    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);
    }

我的客户端看起来像这样:

        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;

问题1:在结果变量的哪个位置,我可以看到“抱歉您的登录失败”的消息? 问题2:返回CreateErrorResponse时,返回HttpStatusCode.OK是否有意义?

1 个答案:

答案 0 :(得分:1)

Q1:来自Response.Content。如果内容类型是application / json,您可以执行以下操作:

response.Content.ReadAsStringAsync().Result;

Q2:如果登录失败,我会返回HttpStatusCode.Unauthorized