I have created Http Trigger Azure Function and its default return type is Task<IActionResult>
.
Is there any difference if I changed it to Task<HttpResponseMessage>
?
Azure function with Task<IActionResult>
return type:
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
Azure function with Task<HttpResponseMessage>
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequestMessage message,
Is there any difference if I changed
Task<IActionResult>
toTask<HttpResponseMessage>
?
You can use the Task<HttpResponseMessage>
to be the return type of your function. There shouldn't be a problem in executing with that.
Having said that, the difference between using the two lies in just the way you return response from your function.
IActionResult
type of response, there is lesser code to write while constructing a response and it makes unit testing simpler.HttpResponseMessage
gives more control on the Http response message sent across the wire.Just as a side note,
In HttpTrigger
Azure function v1.0
, types Task<HttpResponseMessage>
and HttpRequestMessage
were used as defaults for return type and request type respectively.
From v2.0
onwards, types Task<IActionResult>
and HttpRequest
are being used as default return type and request type respectively as it conforms to .net core API structure.
There are 2 main advantages of using the IHttpActionResult
interface.
You can see here.
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Tom" },
new Student() { Id = 2, Name = "Sam" },
new Student() { Id = 3, Name = "John" }
};
public IHttpActionResult Get()
{
return Ok(students);
}
public HttpResponseMessage Get(int id)
{
var student = students.FirstOrDefault(s => s.Id == id);
if (student == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Student not found");
}
return Request.CreateResponse(student);
}
All these methods return a type, that implements IHttpActionResult
interface.
BadRequest()
Conflict()
Created()
InternalServerError()
Redirect()
Unauthorized()
I took reference of this link https://csharp-video-tutorials.blogspot.com/2017/02/ihttpactionresult-vs-httpresponsemessage.html
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.