C#ASP.NET WebAPIでのコントローラーアクションのさまざまな戻り値の種類は何ですか?
Web APIアクションメソッドは、次のリターンタイプを持つことができます。
-
ボイド
-
プリミティブ型/複合型
-
HttpResponseMessage
-
IHttpActionResult
無効 −
すべてのアクションメソッドが何かを返す必要はありません。ボイドリターンタイプにすることができます。
例
using DemoWebApplication.Models
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public void Get([FromBody] Student student){
//Some Operation
}
}
}
void return typeのactionメソッドは、 204 No Contentを返します。 応答。
プリミティブ型/複雑型 −
actionメソッドは、int、stringなどのプリミティブ型、またはListなどの複合型を返すことができます。
例
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public List<string> Get([FromBody] Student student){
return new List<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
}
}
}
HttpResponseMessage −
例
HttpResponseMessageは、アクションメソッドの戻りタイプ(アクション結果)をカスタマイズする場合に使用されます。応答は、ステータスコード、コンテンツタイプ、およびHttpResponseMessageに返されるデータを提供することによってカスタマイズされます。
using DemoWebApplication.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public HttpResponseMessage Get([FromBody] Student student){
if(student.Id > 0){
return Request.CreateResponse(HttpStatusCode.OK, $"The Sudent Id is
{student.Id} and Name is {student.Name}");
} else {
return Request.CreateResponse(HttpStatusCode.BadRequest, $"InValid
Student Id");
}
}
}
}
上記の例では、応答がカスタマイズされていることがわかります。アクションメソッドに送信されるIdは0であるため、elseが実行され、400Badリクエストがエラーメッセージとともに返されます。
IHttpActionResult −
例
IHttpActionResultインターフェイスはWebAPI2で導入されました。基本的に、これはHttpResponseMessageファクトリを定義します。 IHttpActionResultはSystem.Web.Http名前空間に存在します。 HttpResponseMessageよりもIHttpActionResultを使用する利点は次のとおりです。
-
コントローラの単体テストを簡素化します。
-
HTTP応答を作成するための共通ロジックを個別のクラスに移動します。
-
応答の作成に関する低レベルの詳細を非表示にすることで、コントローラーのアクションの意図を明確にします。
例
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class DemoController : ApiController{
public IHttpActionResult Get([FromBody] Student student){
var result = new List<string>{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
return Ok(result);
}
}
}
-
C#ASP.NET WebAPIのアクションメソッドからカスタム結果タイプを返す方法は?
IHttpActionResultインターフェイスを実装することで、結果タイプとして独自のカスタムクラスを作成できます。 。 IHttpActionResultには、HttpResponseMessageインスタンスを非同期的に作成する単一のメソッドExecuteAsyncが含まれています。 public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); } コントロ
-
OSのカーネルとは何ですか?カーネルの種類は何ですか?
すべてのオペレーティングシステム(Windows、Mac、Linux、Android)には、カーネルと呼ばれるコアプログラムがあります。 これは、システム全体の「ボス」として機能します。それがOSの心臓部です!カーネルは、他のすべてを制御するコンピュータプログラムに他なりません。コンピューターで発生することはすべてそれを通過します。この投稿では、OSのカーネルとは何か、およびさまざまな種類のカーネルについて説明します。 OSのカーネルとは OSのコアプログラムであることがわかったので、ブートローダーの後にロードされる最初のプログラムでもあることも知っておく必要があります。次に、ハードウェアと