[英]How i can get the arguments of my Json and validate before of make a post int web api 2 .net?
[英]How can I get the status code of a post to my web api
因此,我的包装盒上有一个URL,当我使用JSON对象(“用户名,密码和applicationId”)将其发布到URL时,它将返回状态代码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);
}
}
使用HttpClient
如下:
网络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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.