In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
The purpose of this article is to share with you what the WebApi interface return values are in C #. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. No return value for void
The void keyword is no stranger to us, which declares that the method does not return a value. Its use is also very simple, let's take a look at an example to understand.
Public class ORDER {public string ID {get; set;} public string NO {get; set;} public string NAME {get; set;} public string DESC {get; set;}} public class OrderController: ApiController {[HttpPost] public void SaveOrder (ORDER name) {/ / processing business logic}}
Call in Web
$(function () {$.ajax ({type: 'post', url:' http://localhost:21528/api/Order/SaveOrder', data: {ID: "aaa", NAME: "test"}, success: function (data, status) {alert (data);}});})
Get the result
As you can see, using the method declared by void, there is no return value in the success method, and the http status code 204 is returned, telling the client that there is no return value for this request.
II. IHttpActionResult
The IHttpActionResult type is a very important return type in WebApi. Below, the blogger will explain some of the uses of this type of return value according to the most commonly used ways in the project.
1. Json (T content)
Friends who have developed using MVC will remember that in MVC, most of the return value types of APIs that request data use JsonResult, and you must have written similar APIs in MVC:
Public JsonResult GetResult () {return Json (new {}, JsonRequestBehavior.AllowGet);}
So, is there a similar usage in WebAPI? Ha ha, on this point, Microsoft is always considerate. In the abstract class ApiController of WebApi, the method Json (T content) is encapsulated for us, and its usage is basically similar to that of JsonResult in MVC. Let's use an example to illustrate its usage:
[HttpGet] public IHttpActionResult GetOrder () {var lstRes = new List (); / / in the actual project, the collection is obtained from the backstage and assigned to the lstRes variable. This is just a test. LstRes.Add (new ORDER () {ID = "aaaa", NO = "111", NAME =" 111", DESC = "1111"}); lstRes.Add (new ORDER () {ID = "bbbb", NO = "222", NAME =" 222", DESC = "2222"}); return Json (lstRes);}
Seeing this code, some people wonder, the return type we defined is IHttpActionResult, is it feasible to return Json (T content) directly? Let's take a look at the definition of Json:
Protected internal JsonResult Json (T content)
Let's move on to the definition of JsonResult
It turns out that JsonResult implements the IHttpActionResult interface, so it's no wonder you can return it directly.
Knowing this, we call it directly through the ajax request in Web:
$(function () {$.ajax ({type: 'get', url:' http://localhost:21528/api/Order/GetOrder', data: {}, success: function (data, status) {alert (data);});})
Let's look at the results:
Since entity classes can be passed directly in this way, what if we want to pass some anonymous types, because in many cases, the objects we need to return to the front end do not have corresponding entities? what if we want to return anonymous objects? We know that the Json (T content) here must pass a corresponding generic type, if it is an anonymous type, it must not be easy to pass here. Fortunately, we have our object type, of course you can use dynamic, let's give it a try.
[HttpGet] public IHttpActionResult GetOrder () {return Json (new {AA = ", BB =" cc "});}
Similarly, look at the test results:
2. Ok (), Ok (T content)
In addition to Json (T content), there is another common method in ApiController: Ok (). Again, we move Ok () to the definition
Protected internal virtual OkResult Ok ()
OkResult goes to definition
With this as a basis, we can rest assured and use it boldly.
[HttpGet] public IHttpActionResult GetOKResult () {return Ok ();}
Get the result
If Ok () is returned, no information is returned to the client, only that the client is told that the request was successful.
In addition to Ok (), there is another overloaded Ok (T content).
[HttpGet] public IHttpActionResult GetOKResult (string name) {return Ok (name);}
This usage is similar to Json (T content), if you have to ask what's the difference between the two, or how to choose between the two. So my understanding is that if you are returning an entity or a collection of entities, it is recommended to use Json (T content), and if you are returning the underlying type (such as int, string, etc.), use Ok (T content).
3. NotFound ()
The NotFound () method is sometimes used when you need to return to the client that a record cannot be found.
Protected internal virtual NotFoundResult NotFound ()
Let's take a look at its usage scenario.
[HttpGet] public IHttpActionResult GetNotFoundResult (string id) {var lstRes = new List (); / / in the actual project, get the collection and assign values to the lstRes variable through the backstage. This is just a test. LstRes.Add (new ORDER () {ID = "aaaa", NO = "111", NAME =" 111", DESC = "1111"}); lstRes.Add (new ORDER () {ID = "bbbb", NO = "222", NAME =" 222", DESC = "2222"}); var oFind = lstRes.FirstOrDefault (x = > x.ID = = id); if (oFind = null) {return NotFound ();} else {return Json (oFind);}}
Get the result
The NotFound () method returns a 404 error to the client.
4. Other
There are other methods, all of which have their specific uses. Post it here.
Content (HttpStatusCode statusCode, T value)
[HttpGet] public IHttpActionResult GetContentResult () {return Content (HttpStatusCode.OK, "OK");}
Returns the value and http status code to the client.
4.2, BadRequest ()
[HttpGet] public IHttpActionResult GetBadRequest (ORDER order) {if (string.IsNullOrEmpty (order.ID)) return BadRequest (); return Ok ();
A http error of 400 is returned to the client.
4.3The Redirect (string location)
[HttpGet] public IHttpActionResult RedirectResult () {return Redirect ("http://localhost:21528/api/Order/GetContentResult");}]
Redirect the request to another location.
5. Implementation of custom IHttpActionResult interface
The above describes some common methods to implement the IHttpActionResult interface built into the system. What if we need to customize the return of IHttpActionResult?
Before introducing it, it is necessary to take a look at the definition of the IHttpActionResult type. If you change the IHttpActionResult to the definition, you can see:
Namespace System.Web.Http {/ / abstract: / / Defines a command that asynchronously creates an System.Net.Http.HttpResponseMessage. Public interface IHttpActionResult {/ / abstract: / / Creates an System.Net.Http.HttpResponseMessage asynchronously. / Parameter: / / cancellationToken: / / The token to monitor for cancellation requests. / return result: / / A task that, when completed, contains the System.Net.Http.HttpResponseMessage. Task ExecuteAsync (CancellationToken cancellationToken);}}
This interface contains a unique method, ExecuteAsync (), which asynchronously creates an instance of HttpResponseMessage and returns it to the client.
With this as a basis, let's customize a subclass of bootstrapTable server paging to demonstrate the use of custom IHttpActionResult.
First, customize an implementation class
Public class PageResult: IHttpActionResult {object _ value; HttpRequestMessage _ request; public PageResult (object value, HttpRequestMessage request) {_ value = value; _ request = request;} public Task ExecuteAsync (System.Threading.CancellationToken cancellationToken) {var response = new HttpResponseMessage () {Content = new ObjectContent (typeof (object), _ value, new JsonMediaTypeFormatter (), RequestMessage = _ request}; return Task.FromResult (response);}}
Then, return the PageResult object in the API interface
[HttpGet] public IHttpActionResult GetPageRow (int limit, int offset) {var lstRes = new List (); / / in the actual project, the collection is fetched from the backend and assigned to the lstRes variable. This is just a test. LstRes.Add (new ORDER () {ID = "aaaa", NO = "111", NAME =" 111", DESC = "1111"}); lstRes.Add (new ORDER () {ID = "bbbb", NO = "222", NAME =" 222", DESC = "2222"}); var oData = new {total = lstRes.Count, rows = lstRes.Skip (offset) .Take (limit). ToList ()}; return new PageResult (oData, Request);}
Preferably, the ajax call
$(function () {$.ajax ({type: 'get', url:' http://localhost:21528/api/Order/GetPageRow', data: {limit:1,offset:1}, success: function (data, status) {alert (data);}});})
Get the result
III. HttpResponseMessage
The object HttpResponseMessage was mentioned above when customizing the IHttpActionResult return type. It represents a message object that returns a http response to the client (containing the http status code and the message that needs to be returned to the client). This object also has its own unique usage scenario: it is used when you need to return HttpResponse to the client. Take the export as an example, because the exported Excel file needs to be exported to the client browser, the server of Webapi needs to output the file stream to the client of Web. At this time, the general IHttpActionResult object is not convenient to solve this problem, so HttpReponseMessage comes in handy. Let's take a look at an example of its use.
Public HttpResponseMessage Export () {/ / fetch data var lstRes = OrderBLL.Export (); / / populate Excel with data HSSFWorkbook workbook = new HSSFWorkbook (); CreateAndFillSheet (workbook, lstRes); / / Save to service var fileName = "Excel" + DateTime.Now.ToString ("yyyyMMddHHmmss") + ".xls"; var strPath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, @ "Data\" + fileName) Using (FileStream fs = new FileStream (strPath, FileMode.Create)) {workbook.Write (fs); using (MemoryStream ms = new MemoryStream ()) {workbook.Write (ms);}} / / output to browser try {var stream = new FileStream (strPath, FileMode.Open); HttpResponseMessage response = new HttpResponseMessage (HttpStatusCode.OK); response.Content = new StreamContent (stream) Response.Content.Headers.ContentType = new MediaTypeHeaderValue ("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") {FileName = fileName}; return response;} catch {return new HttpResponseMessage (HttpStatusCode.NoContent);}}
Save the file stream in a StreamContent object and output it to a browser. The Excel can be output on the browser side.
IV. Custom types
The above return value types can solve most of our return value problems. Of course, you can also return any type of webapi API like the ordinary method. WebApi will automatically serialize any custom return type, and then write the serialized value to the response body, and the status code will return 200. For example:
[HttpGet] public object GetOther () {var lstRes = new List (); / / in the actual project, the collection is obtained from the backstage and assigned to the lstRes variable. This is just a test. LstRes.Add (new ORDER () {ID = "aaaa", NO = "111", NAME =" 111", DESC = "1111"}); lstRes.Add (new ORDER () {ID = "bbbb", NO = "222", NAME =" 222", DESC = "2222"}); return lstRes;}
Get the result
And the above Json, Ok and other uses in the effect is not much different.
Thank you for reading! This is the end of the article on "what are the return values of the WebApi interface in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.