MVC request to Web Api - c#

I'm trying to build an MVC that requests through a PCL to a WebApi. I am sending a get requests and getting stuck on the awaiting for the response. Postman returns the correct values. I also don t get exceptions on send. The 3 projects are both on the same solution.
PCL
HttpResponseMessage httpResponse = null;
try
{
httpResponse = await _http.GetAsync( "http://localhost:43818/api/values" );
}
catch (Exception e)
{
var meessage = e.Message;
var stack = e.StackTrace;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
string json = await httpResponse.Content.ReadAsStringAsync( );
}
So the issue is that in the PCL, it's doesn pass the await, it gets stuck.
MVC
var result = apiClient.GetIndex( );
Web Api
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Also, how do i wait in my MVC for the response before rendering the controller view

In your Class library (PCL), Create method GetIndex as below,
public async Task GetIndexAsync()
{
HttpResponseMessage httpResponse = null;
try
{
_http.BaseAddress = new Uri("http://localhost:43818/");
httpResponse = await _http.GetAsync("api/values");
}
catch (Exception e)
{
var meessage = e.Message;
var stack = e.StackTrace;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
string json = await httpResponse.Content.ReadAsStringAsync();
}
}
And In MVC calling method as below,
var result = apiClient.GetIndexAsync().Wait();
which solved both your problems.

Ok so i found the best sollution. Blocking threads is not a very good idea.
This is the fix
PCL
public async Task<HttpResponseMessage> Register()
{
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = new Uri( _http.BaseAddress, "account/register/" ),
Method = HttpMethod.Post,
Content = new StringContent( "{\"Email\": \"email#yahoo.com\",\"Password\": \"Password!1\",\"ConfirmPassword\": \"Password!1\"}",
Encoding.UTF8,
_contentType
),
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await _http.SendAsync( request, CancellationToken.None );
}
catch (Exception e)
{
Debugger.Break();
}
return response;
}
MVC Client
public async Task<ViewResult> Index( )
{
var thisTask = await Api.Register( );
return View();
}

Related

Http Get Request not getting any data

I have my Web Api on a production server online and working well in postman and in Xamarin forms so far until I needed to do a Get Request and does not return any data. Infact it stops at the GetAsStringAsync line and does not continue. Instead, it jumps out of the method and then nothing more.
Does any one know what the problem could be? I have checked and made sure my Internet is working and the Uri too.
This is where I am doing my Get in Xamarin forms:
public async Task<List<OfferModel>> AllOffers()
{
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
//it does not continue after this line, it jumps out of the method instead
var response = await httpclient.GetStringAsync(UrlConstants.offerurl);
var data =JsonConvert.DeserializeObject<List<OfferModel(response);
return data;
}
Solution 1
Can you try access task via awaiter it may be wait until result when responded
public class HttpHelperService
{
public async Task<List<OfferModel>> AllOffers()
{
List<OfferModel> result;
string responseBody;
using (HttpClient client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
HttpResponseMessage response = client.GetStringAsync(new Uri(UrlConstants.offerurl)).GetAwaiter().GetResult();
result = JsonConvert.DeserializeObject<List<OfferModel>>(response);
}
catch (Exception ex)
{
result = null;
}
return result;
}
}
}
Solution 2
public class MyPage : ContentPage
{
//Here is your page constructor
public MyPage()
{
GetServices(); //--> call here without awaiter
}
}
//Here is your awaiter method
private async void GetServices()
{
LoadingPopupService.Show();
var result = await HttpService.AllOffers();
LoadingPopupService.Hide();
}
//Here is your service.
public async Task<List<OfferModel>> AllOffers()
{
var httpclient = new HttpClient();
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
var response = await httpclient.GetStringAsync(UrlConstants.offerurl);
var data =JsonConvert.DeserializeObject<List<OfferModel(response);
return data;
}

WebAPi - unify error messages format from ApiController and OAuthAuthorizationServerProvider

In my WebAPI project I'm using Owin.Security.OAuth to add JWT authentication.
Inside GrantResourceOwnerCredentials of my OAuthProvider I'm setting errors using below line:
context.SetError("invalid_grant", "Account locked.");
this is returned to client as:
{
"error": "invalid_grant",
"error_description": "Account locked."
}
after user gets authenticated and he tries to do "normal" request to one of my controllers he gets below response when model is invalid (using FluentValidation):
{
"message": "The request is invalid.",
"modelState": {
"client.Email": [
"Email is not valid."
],
"client.Password": [
"Password is required."
]
}
}
Both requests are returning 400 Bad Request, but sometimes You must look for error_description field and sometimes for message
I was able to create custom response message, but this only applies to results I'm returning.
My question is: is it possible to replace message with error in response that is returned by ModelValidatorProviders and in other places?
I've read about ExceptionFilterAttribute but I don't know if this is a good place to start. FluentValidation shouldn't be a problem, because all it does is adding errors to ModelState.
EDIT:
Next thing I'm trying to fix is inconsistent naming convention in returned data across WebApi - when returning error from OAuthProvider we have error_details, but when returning BadRequest with ModelState (from ApiController) we have modelState. As You can see first uses snake_case and second camelCase.
UPDATED ANSWER (Use Middleware)
Since the Web API original delegating handler idea meant that it would not be early enough in the pipeline as the OAuth middleware then a custom middleware needs to be created...
public static class ErrorMessageFormatter {
public static IAppBuilder UseCommonErrorResponse(this IAppBuilder app) {
app.Use<JsonErrorFormatter>();
return app;
}
public class JsonErrorFormatter : OwinMiddleware {
public JsonErrorFormatter(OwinMiddleware next)
: base(next) {
}
public override async Task Invoke(IOwinContext context) {
var owinRequest = context.Request;
var owinResponse = context.Response;
//buffer the response stream for later
var owinResponseStream = owinResponse.Body;
//buffer the response stream in order to intercept downstream writes
using (var responseBuffer = new MemoryStream()) {
//assign the buffer to the resonse body
owinResponse.Body = responseBuffer;
await Next.Invoke(context);
//reset body
owinResponse.Body = owinResponseStream;
if (responseBuffer.CanSeek && responseBuffer.Length > 0 && responseBuffer.Position > 0) {
//reset buffer to read its content
responseBuffer.Seek(0, SeekOrigin.Begin);
}
if (!IsSuccessStatusCode(owinResponse.StatusCode) && responseBuffer.Length > 0) {
//NOTE: perform your own content negotiation if desired but for this, using JSON
var body = await CreateCommonApiResponse(owinResponse, responseBuffer);
var content = JsonConvert.SerializeObject(body);
var mediaType = MediaTypeHeaderValue.Parse(owinResponse.ContentType);
using (var customResponseBody = new StringContent(content, Encoding.UTF8, mediaType.MediaType)) {
var customResponseStream = await customResponseBody.ReadAsStreamAsync();
await customResponseStream.CopyToAsync(owinResponseStream, (int)customResponseStream.Length, owinRequest.CallCancelled);
owinResponse.ContentLength = customResponseStream.Length;
}
} else {
//copy buffer to response stream this will push it down to client
await responseBuffer.CopyToAsync(owinResponseStream, (int)responseBuffer.Length, owinRequest.CallCancelled);
owinResponse.ContentLength = responseBuffer.Length;
}
}
}
async Task<object> CreateCommonApiResponse(IOwinResponse response, Stream stream) {
var json = await new StreamReader(stream).ReadToEndAsync();
var statusCode = ((HttpStatusCode)response.StatusCode).ToString();
var responseReason = response.ReasonPhrase ?? statusCode;
//Is this a HttpError
var httpError = JsonConvert.DeserializeObject<HttpError>(json);
if (httpError != null) {
return new {
error = httpError.Message ?? responseReason,
error_description = (object)httpError.MessageDetail
?? (object)httpError.ModelState
?? (object)httpError.ExceptionMessage
};
}
//Is this an OAuth Error
var oAuthError = Newtonsoft.Json.Linq.JObject.Parse(json);
if (oAuthError["error"] != null && oAuthError["error_description"] != null) {
dynamic obj = oAuthError;
return new {
error = (string)obj.error,
error_description = (object)obj.error_description
};
}
//Is this some other unknown error (Just wrap in common model)
var error = JsonConvert.DeserializeObject(json);
return new {
error = responseReason,
error_description = error
};
}
bool IsSuccessStatusCode(int statusCode) {
return statusCode >= 200 && statusCode <= 299;
}
}
}
...and registered early in the pipeline before the the authentication middlewares and web api handlers are added.
public class Startup {
public void Configuration(IAppBuilder app) {
app.UseResponseEncrypterMiddleware();
app.UseRequestLogger();
//...(after logging middle ware)
app.UseCommonErrorResponse();
//... (before auth middle ware)
//...code removed for brevity
}
}
This example is just a basic start. It should be simple enough able to extend this starting point.
Though in this example the common model looks like what is returned from OAuthProvider, any common object model can be used.
Tested it with a few In-memory Unit Tests and through TDD was able to get it working.
[TestClass]
public class UnifiedErrorMessageTests {
[TestMethod]
public async Task _OWIN_Response_Should_Pass_When_Ok() {
//Arrange
var message = "\"Hello World\"";
var expectedResponse = "\"I am working\"";
using (var server = TestServer.Create<WebApiTestStartup>()) {
var client = server.HttpClient;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(message, Encoding.UTF8, "application/json");
//Act
var response = await client.PostAsync("/api/Foo", content);
//Assert
Assert.IsTrue(response.IsSuccessStatusCode);
var result = await response.Content.ReadAsStringAsync();
Assert.AreEqual(expectedResponse, result);
}
}
[TestMethod]
public async Task _OWIN_Response_Should_Be_Unified_When_BadRequest() {
//Arrange
var expectedResponse = "invalid_grant";
using (var server = TestServer.Create<WebApiTestStartup>()) {
var client = server.HttpClient;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(expectedResponse, Encoding.UTF8, "application/json");
//Act
var response = await client.PostAsync("/api/Foo", content);
//Assert
Assert.IsFalse(response.IsSuccessStatusCode);
var result = await response.Content.ReadAsAsync<dynamic>();
Assert.AreEqual(expectedResponse, (string)result.error_description);
}
}
[TestMethod]
public async Task _OWIN_Response_Should_Be_Unified_When_MethodNotAllowed() {
//Arrange
var expectedResponse = "Method Not Allowed";
using (var server = TestServer.Create<WebApiTestStartup>()) {
var client = server.HttpClient;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Act
var response = await client.GetAsync("/api/Foo");
//Assert
Assert.IsFalse(response.IsSuccessStatusCode);
var result = await response.Content.ReadAsAsync<dynamic>();
Assert.AreEqual(expectedResponse, (string)result.error);
}
}
[TestMethod]
public async Task _OWIN_Response_Should_Be_Unified_When_NotFound() {
//Arrange
var expectedResponse = "Not Found";
using (var server = TestServer.Create<WebApiTestStartup>()) {
var client = server.HttpClient;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Act
var response = await client.GetAsync("/api/Bar");
//Assert
Assert.IsFalse(response.IsSuccessStatusCode);
var result = await response.Content.ReadAsAsync<dynamic>();
Assert.AreEqual(expectedResponse, (string)result.error);
}
}
public class WebApiTestStartup {
public void Configuration(IAppBuilder app) {
app.UseCommonErrorMessageMiddleware();
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
}
public class FooController : ApiController {
public FooController() {
}
[HttpPost]
public IHttpActionResult Bar([FromBody]string input) {
if (input == "Hello World")
return Ok("I am working");
return BadRequest("invalid_grant");
}
}
}
ORIGINAL ANSWER (Use DelegatingHandler)
Consider using a DelegatingHandler
Quoting from an article found online.
Delegating handlers are extremely useful for cross cutting concerns.
They hook into the very early and very late stages of the
request-response pipeline making them ideal for manipulating the
response right before it is sent back to the client.
This example is a simplified attempt at the unified error message for HttpError responses
public class HttpErrorHandler : DelegatingHandler {
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
var response = await base.SendAsync(request, cancellationToken);
return NormalizeResponse(request, response);
}
private HttpResponseMessage NormalizeResponse(HttpRequestMessage request, HttpResponseMessage response) {
object content;
if (!response.IsSuccessStatusCode && response.TryGetContentValue(out content)) {
var error = content as HttpError;
if (error != null) {
var unifiedModel = new {
error = error.Message,
error_description = (object)error.MessageDetail ?? error.ModelState
};
var newResponse = request.CreateResponse(response.StatusCode, unifiedModel);
foreach (var header in response.Headers) {
newResponse.Headers.Add(header.Key, header.Value);
}
return newResponse;
}
}
return response;
}
}
Though this example is very basic, it is trivial to extend it to suit your custom needs.
Now it is just a matter of adding the handler to the pipeline
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.MessageHandlers.Add(new HttpErrorHandler());
// Other code not shown...
}
}
Message handlers are called in the same order that they appear in
MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is
the first to get the response message.
Source: HTTP Message Handlers in ASP.NET Web API
is it possible to replace message with error in response that is
returned by ModelValidatorProviders
We may use overloaded SetError to do it otherwise, replace error with message.
BaseValidatingContext<TOptions>.SetError Method (String)
Marks this context as not validated by the application and assigns various error information properties. HasError becomes true and IsValidated becomes false as a result of calling.
string msg = "{\"message\": \"Account locked.\"}";
context.SetError(msg);
Response.StatusCode = 400;
context.Response.Write(msg);

creating web api and calling asynchronous

I am creating web api. I want to call in bot messenger framework.
In web api controller i have method :
public async Task<HttpResponseMessage> Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, DateTime.UtcNow.ToString());
return response;
}
In the bot framework i have this code :
public static async Task<List<EventModel>> Response(string uri)
{
//string escapeString = Uri.EscapeDataString(phrase);
string returnValue = string.Empty;
try
{
using (var client = new HttpClient())
{
var message = await client.GetAsync(uri);
if (message.IsSuccessStatusCode)
{
var jsonResponse = await message.Content.ReadAsStringAsync();
jsonResponse = jsonResponse.TrimStart('\"');
jsonResponse = jsonResponse.TrimEnd('\"');
jsonResponse = jsonResponse.Replace("\\", "");
var data = JsonConvert.DeserializeObject<List<EventModel>>(jsonResponse);
return data;
}
else return null;
}
}
catch (Exception exc)
{
return null;
}
}
the problem : client.GetAsync(uri) never ends.
Some help ?

Error handling (Sending ex.Message to the client)

I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors out.
I have tried so many things, but nothing implements IActionResult.
I don't understand why this isn't a common thing that people need. If there truthfully is no solution can someone tell me why?
I do see some documentation out there using HttpResponseException(HttpResponseMessage), but in order to use this, I have to install the compat shim. Is there a new way of doing these things in Core 1.0?
Here is something I have been trying with the shim but it isn't working:
// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
Customer c = _customersService.GetCustomerById(id);
if (c == null)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response);
//return NotFound();
}
return new ObjectResult(c);
}
When the HttpResponseException is thrown, I look on the client and can't find the message I am sending anything in the content.
Here is an simple error DTO class
public class ErrorDto
{
public int Code {get;set;}
public string Message { get; set; }
// other fields
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
And then using the ExceptionHandler middleware:
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorDto()
{
Code = <your custom code based on Exception Type>,
Message = ex.Message // or your custom message
// other custom data
}.ToString(), Encoding.UTF8);
}
});
});
Yes it is possible to change the status code to whatever you need:
In your CustomExceptionFilterAttribute.cs file modify the code as follows:
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
context.Result = new ContentResult
{
Content = $"Error: {exception.Message}",
ContentType = "text/plain",
// change to whatever status code you want to send out
StatusCode = (int?)HttpStatusCode.BadRequest
};
}
}
That's pretty much it.
If you have custom exceptions, then you can also check for them when grabbing the thrown exception from the context. Following on from that you can then send out different HTTP Status Codes depdending on what has happened in your code.
Hope that helps.
You can create a custom Exception Filter like below
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
context.Result = new JsonResult(exception.Message);
}
}
Then apply the above attribute to your controller.
[Route("api/[controller]")]
[CustomExceptionFilter]
public class ValuesController : Controller
{
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
throw new Exception("Suckers");
return new string[] { "value1", "value2" };
}
}
Rather than raising and catching an exception, how about you simplify your action to:
// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
var customer = _customersService.GetCustomerById(id);
if (customer == null)
{
return NotFound("Customer doesn't exist");
}
return Ok(customer);
}
I wrote a blog post with some more options such as returning a JSON object instead of text.
Maybe that is helpful. You can return just object and sent for example a BadRequest (HTTP CODE: 400) with your custom object as actual parameter (I just used an interpolated string here) but you can put in anything.
In your client side you can catch that error situation for example with an AJAX error handler.
// GET: api/TruckFahrerGeoData
[HttpGet]
public object GetTruckFahrerGeoData()
{
var truckFahrerGeoDataItems = new List<TruckFahrerGeoDataViewModel>();
var geodataItems = _context.TruckFahrerGeoData;
foreach (var truckFahrerGeoData in geodataItems)
{
GeoTelemetryData geoTelemetryData = JsonConvert.DeserializeObject<GeoTelemetryData>(truckFahrerGeoData.TelemetryData);
if (geoTelemetryData == null)
{
return BadRequest($"geoTelemetryData null for id: {truckFahrerGeoData.Id}");
}
TruckFahrerGeoDataViewModel truckFahrerGeoDataViewModel = new TruckFahrerGeoDataViewModel
{
Speed = geoTelemetryData.Speed,
Accuracy = geoTelemetryData.Accuracy,
TruckAppId = geoTelemetryData.Activity.TruckAppId,
TruckAuftragStatusId = geoTelemetryData.Activity.TruckAuftragStatusId,
ClId = geoTelemetryData.Activity.ClId,
TruckAuftragLaufStatusId = geoTelemetryData.Activity.TruckAuftragLaufStatusId,
TaskId = geoTelemetryData.Activity.TaskId,
TruckAuftragWorkflowStatusId = geoTelemetryData.Activity.TruckAuftragWorkflowStatusId
};
truckFahrerGeoDataItems.Add(truckFahrerGeoDataViewModel);
}
return truckFahrerGeoDataItems;
}
Or an even more cleaner way with IActionResult like that way:
// GET: api/TruckFahrerGeoData
[HttpGet]
public IActionResult GetTruckFahrerGeoData()
{
var truckFahrerGeoDataItems = new List<TruckFahrerGeoDataViewModel>();
var geodataItems = _context.TruckFahrerGeoData;
foreach (var truckFahrerGeoData in geodataItems)
{
GeoTelemetryData geoTelemetryData = JsonConvert.DeserializeObject<GeoTelemetryData>(truckFahrerGeoData.TelemetryData);
if (geoTelemetryData == null)
{
return BadRequest($"geoTelemetryData null for id: {truckFahrerGeoData.Id}");
}
TruckFahrerGeoDataViewModel truckFahrerGeoDataViewModel = new TruckFahrerGeoDataViewModel
{
Speed = geoTelemetryData.Speed,
Accuracy = geoTelemetryData.Accuracy,
TruckAppId = geoTelemetryData.Activity.TruckAppId,
TruckAuftragStatusId = geoTelemetryData.Activity.TruckAuftragStatusId,
ClId = geoTelemetryData.Activity.ClId,
TruckAuftragLaufStatusId = geoTelemetryData.Activity.TruckAuftragLaufStatusId,
TaskId = geoTelemetryData.Activity.TaskId,
TruckAuftragWorkflowStatusId = geoTelemetryData.Activity.TruckAuftragWorkflowStatusId
};
truckFahrerGeoDataItems.Add(truckFahrerGeoDataViewModel);
}
return Ok(truckFahrerGeoDataItems);
}
Late to the party but refining the answer .
Define your error response class with minimum below attributes
using Microsoft.AspNetCore.Http;
public class ErrorResponse
{
private readonly RequestDelegate next;
public ErrorResponse(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context )
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = HttpStatusCode.InternalServerError;
string result = string.Empty;
object data = new object();
if (ex is ForbiddenException)
{
code = HttpStatusCode.Forbidden;
result = JsonConvert.SerializeObject(new Response<object>(Status.Forbidden(ex.Message), data));
}
else if(ex is BadRequestException){
code = HttpStatusCode.BadRequest;
result = JsonConvert.SerializeObject(new Response<object>(Status.BadRequest(ex.Message), data));
}
else if (ex is NotFoundException)
{
code = HttpStatusCode.NotFound;
result = JsonConvert.SerializeObject(new Response<object>(Status.NotFound(ex.Message), data));
}
else if (ex is UnauthorizedException)
{
code = HttpStatusCode.Unauthorized;
result = JsonConvert.SerializeObject(new Response<object>(Status.Unauthorized(ex.Message), data));
}
else
{
result = JsonConvert.SerializeObject(new Response<object>(Status.InternalServerError(ex.Message), data));
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
Next use this class as middleware in startup.cs class
app.UseHttpsRedirection();
app.UseMiddleware(typeof(ErrorResponse));
Now each request and response will go through this class,if an error occurs then error code will be set to true with error code. A sample response like below
data: {}
status: {
code: 404
error: true
message: "No employee data found"
type: "Not Found"
}
I had the same problem and after some research, I found out I could use HttpClient to call my API and read the response easily. HttpClient does not throw any error when the HTTP response contains an error code, but it sets the IsSuccessStatusCode property to false.
This is my function using the HttpClient. I call this from my controller.
public static async Task<HttpResponseMessage> HttpClientPost(string header, string postdata, string url)
{
string uri = apiUrl + url;
using (var client = new HttpClient())
{
//client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", header);
HttpResponseMessage response = await client.PostAsync(uri, new StringContent(postdata));
return response;
}
}
This is my controller code, where I call the function and read the response and determine whether I have an error or not and respond accordingly. Note that I am checking the IsSuccessStatusCode.
HttpResponseMessage response;
string url = $"Setup/AddDonor";
var postdata = JsonConvert.SerializeObject(donor);
response = await ApiHandler.HttpClientPost(HttpContext.Session.GetString(tokenName), postdata, url);
//var headers = response.Headers.Concat(response.Content.Headers);
var responseBody = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
tnxresult = JsonConvert.DeserializeObject<TnxResult>(AppFunctions.CleanResponse(responseBody));
return Json(new
{
ok = true,
message = tnxresult.Message,
statusCode = tnxresult.StatusCode
});
}
else
{
ApiError rs = JsonConvert.DeserializeObject<ApiError>(AppFunctions.CleanResponse(responseBody));
return Json(new
{
ok = false,
message = rs.Message,
statusCode = rs.StatusCode
});
}
My API returns error messages in JSON. If the call is successful, I am packing the response in JSON too.
The crucial line of code is this one...
var responseBody = await response.Content.ReadAsStringAsync();
It serializes the HTTP content to a string as an asynchronous operation.
After that I can convert my JSON string to an object and access the error/success message and the Status Code too.

Async method does not return asp.net mvc 4

I'm having a problem with an async method that I implemented. The method basically makes a HttpRequest to a resource and deserializes the string if the request is successful. I wrote a test for the method, and it works. But the method does never return when I call it from a controller?
public async Task<IEnumerable<T>> Get()
{
try
{
var resourceSegmentUri = new Uri(_uri, UriKind.Relative);
var response = await _client.GetAsync(resourceSegmentUri);
if (response.IsSuccessStatusCode)
{
var submission = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<T>>(submission);
}
if (response.Content != null)
{
var message = response.Content.ReadAsStringAsync();
throw new WebException(message.Result, (WebExceptionStatus)response.StatusCode);
}
}
catch (WebException e)
{
Logger.Error("GET Request failed with status: {0}", e.Status);
throw;
}
throw new Exception();
}
Code that never returns:
public ActionResult Index()
{
var api = new Api();
var test = api.Get().Result; //Never returns
return View();
}
Test that works:
[Test]
public void GetShouldReturnIfSuccessfulRequest()
{
var api = new Api();
var submission = api.Get();
Console.WriteLine(JsonConvert.SerializeObject(submission));
Assert.NotNull(submission);
}
Does anyone know the problem?
You've got a deadlock because you're calling .Result in your controller action.
If you use async/await then you have to use asynchronous actions too.
So something like this should fix it:
public async Task<ActionResult> Index()
{
var api = new Api();
var test = await api.Get(); // Should return
}
There's a comprehensive article about this here: Using Asynchronous Methods in ASP.NET MVC 4

Categories

Resources