I'm still learning c# web API at the moment, and I've faced some problems.
so the code snippet below shows a portion of my codes that will create a new student in the database, what I am trying to do is to create the object and if it succeeded, it will return a HTTP-CREATED http response code and return the STUDENT OBJECT.
if it fails, it should return a HTTP-BADREQUEST response code and ALSO return the STUDENT OBJECT.
HOWEVER, in order to return the response code, I am unable to return a student object and vice-versa due to the return type set, hence, the dilemma.
// POST api/student
public HttpResponseMessage PostStudent(Models.Student student)
{
if (DBManager.createStudent(student) != null)
return new HttpResponseMessage(HttpStatusCode.Created);
// HOW TO RETURN STUDENT OBJECT?
else
return new HttpResponseMessage(HttpStatusCode.BadRequest);
// HOW TO RETURN STUDENT OBJECT?
}
HttpRequestMessageExtensions.CreateResponse<T> Method
具有一个可选的正式参数,称为value
,可用于创建同时包含状态代码和对象的HttpResponseMessage
。
return Request.CreateResponse(HttpStatusCode.Created, student);
I'll tell you my own experience of building a web server for my company: DON'T use WebApi. There are so many limitations and in short, supports a very narrow usage scenario. Just stick to the traditional MVC controllers and life is much easier:
public ActionResult PostStudent(Models.Student s){
//do something
Response.StatusCode = 400;
return Json(s);
}
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.