如何获取帖子的状态代码到我的web api

时间:2014-02-11 15:44:08

标签: c# asp.net api httprequest httpresponse

所以我的盒子上有一个URL,当我用JSON对象("用户名,密码和applicationId")发布它时,它将返回状态代码200,400,505等。 ..当我使用Chromes Advanced Rest Client发布到网址时,一切正常。因此,我决定创建一个单页Web应用程序项目,该项目将具有发布到此URL的登录名。现在我的问题是我无法弄清楚如何获取响应状态代码。每当我发出请求时它都会处理掉,这样我就无法获得响应的状态代码。

我正在试图想出一种获得响应状态代码的方法。为了获得状态代码,我到底需要做什么?到目前为止,我已尝试使用WebClient,HttpWebRequest和HttpRequest。所有这些最终都被处理掉了,我无法得到答复。我现在还不确定该做什么。如果你能指出我正确的方向,我们将不胜感激。

 public class ValidationController : ApiController
{
    // POST api/account
    /// <summary>
    /// This will return a 200 and a JWT token if successful
    /// </summary>
    /// <param name="value">Json '{"Username":"[your_username]", "Password":"[your_password]","Application":"[your_application_name]"}'</param>
    /// <returns>OnSuccess 200 and JWT token, OnFailure 401 and nothing else</returns>
    public HttpResponseMessage Post([FromBody]Login login)
    //public HttpResponseMessage Post([FromBody]string value)
    {
        //var login = new Login();
        if (Request.RequestUri.Scheme != "https")
        {
            return Request.CreateResponse<string>(HttpStatusCode.HttpVersionNotSupported, "Authentication Failed.  Must use HTTPS.");
        }
        if (login == null)
        {
            return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The login piece is null");
        }
        if (Authenticate(login) == "-1")
        {
            return Request.CreateResponse<string>(HttpStatusCode.Unauthorized, "Authentication Failed");
        }
        return CreateToken(login);
    }

}

1 个答案:

答案 0 :(得分:1)

以下是使用HttpClient

执行此操作的方法

Web API

public HttpResponseMessage Get()
        {
            HttpResponseMessage response;

            var students = _starterKitUnitOfWork.StudentRepository.Get();

            if (students == null)
            {
                response = new HttpResponseMessage(HttpStatusCode.NotFound);
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.OK, students);
                response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
            }
            return response;
        }

MVC客户端:

     public async Task<IEnumerable<Student>> GetStudents()
            {           
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(ConfigurationManager.AppSettings["BaseAddress"]);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var response = await client.GetAsync("student").ConfigureAwait(false);
                    var statusCode = response.StatusCode; //HERE IT IS
                    return response.Content.ReadAsAsync<IEnumerable<Student>>().Result;
                    }    
            }