I have following C# method that uses System.Threading.Tasks.Task class.
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.InternalServerError);
response.Content = new StringContent(Content);
response.RequestMessage = Request;
return Task.FromResult(response);
}
I am having some issues writing above code in VB.Net. I have tried the following, but VS 2107 shows an error for the last line in the below function saying FromResult is not a member of Task
.
Question: What would be correct equivalent of C# code in VB.Net for the last line in C# method?
Public Async Function ExecuteAsync(ByVal cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
Dim response As HttpResponseMessage = New HttpResponseMessage(HttpStatusCode.InternalServerError)
response.Content = New StringContent(Content)
response.RequestMessage = Request
Return Task.FromResult(Of HttpResponseMessage) (response) 'this line shows error
End Function
Screenshot of error
The full C# class that contains this original method is as below.
public class GlobalExceptionHandler : ExceptionHandler
{
public GlobalExceptionHandler()
{
//
// TODO: Add constructor logic here
//
}
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new TextPlainErrorResult
{
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Our team has been informed and we will try to fix it as soon as possible."
};
base.Handle(context);
}
private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.InternalServerError);
response.Content = new StringContent(Content);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
}
The converted VB.Net code of above C# code is as below.
Public Class GlobalExceptionHandler
Inherits ExceptionHandler
Public Sub New()
End Sub
Public Overrides Sub Handle(ByVal context As ExceptionHandlerContext)
context.Result = New TextPlainErrorResult With {
.Request = context.ExceptionContext.Request,
.Content = "Oops! Sorry! Something went wrong." & "Our team has been informed and we will try to fix it as soon as possible."
}
MyBase.Handle(context)
End Sub
Private Class TextPlainErrorResult
Implements IHttpActionResult
Public Property Request As HttpRequestMessage
Public Property Content As String
Public Function ExecuteAsync(ByVal cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
Dim response As HttpResponseMessage = New HttpResponseMessage(HttpStatusCode.InternalServerError)
response.Content = New StringContent(Content)
response.RequestMessage = Request
Return new Task.FromResult(response)
End Function
End Class
End Class