WebApi and Swagger - asp.net

I am using asp.net webapi and using swagger to create a RestApi within a WPF app via AutoRest.
I am having problem figuring out how to consume the returned data if there is an error.
My controller is as follows;
// POST: api/Personnel
//[SwaggerResponse(HttpStatusCode.InternalServerError ,Type = typeof(HttpError))]
[SwaggerOperation("AddEditContract")]
[SwaggerResponse(HttpStatusCode.OK, Description = "Add/Edit a Contract", Type =typeof(int))]
public IHttpActionResult Post(ContractDto value)
{
try
{
var _contractsService = new Business.ContractsService();
var contractToSave = _contractsService.GetContractsById(value.CC_Id);
if (contractToSave == null)
{
return NotFound();
}
var ret = _contractsService.SaveContract(value);
if (ret > 0)
{
return Ok(ret);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
I happened to have an error appear within the WebApi based on an error with AutoMapper but it was getting swallowed up. It is returning an error message in the response, which is great.
Here is the current AutoRest code for this call.
public static int? AddEditContract(this IBuxtedConAPI operations, ContractDto value)
{
return Task.Factory.StartNew(s => ((IBuxtedConAPI)s).AddEditContractAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
As you can see its expecting an int. If I uncomment the
//[SwaggerResponse(HttpStatusCode.InternalServerError ,Type = typeof(HttpError))]
The int return type turns to object.
So the real question.
Here is my service call from WPF to the WebApi
public async Task<int> SaveContract(ContractDto entity)
{
using (var db = new BuxtedConAPI())
{
var ret = await db.AddEditContractAsync(entity);
return (int)ret;
}
}
If an object is returned how do I pick up if an error has occurred or if the simple int (with a success) is just returned.
Thanks in advance.
Scott

Can you post the swagger file that you're generating and passing to AutoRest?
The reason return type turns to object (or whatever common base class is shared between all the possible responses), is because AutoRest treats explicitly defined responses as return values. Exceptions are used only for the default response.
We're investigating ways to specify multiple error responses that will generate the appropriate exceptions.

Related

How can I use a default value/model on WebAPI EmptyBody?

I have dotnet WebAPI and I'm trying to get a specific behaviour but am constantly getting 415 responses.
I have reproduced this by starting a new webapi project using dotnet new webapi on the command line. From there, I added two things: a new controller, and a model class. In my real project the model class is obviously a bit more complex, with inheritance and methods etc...
Here they are:
[HttpGet("/data")]
public async Task<IActionResult> GetModel(BodyParams input)
{
var response = new { Message = "Hello", value = input.valueOne };
return Ok(response);
}
public class BodyParams {
public bool valueOne { get; set; } = true;
}
My goal is that the user can call https://localhost:7222/data with no headers or body needed at all, and will get the response - BodyParams will be used with the default value of true. Currently, from postman, or from the browser, I get a 415 response.
I've worked through several suggestions on stack and git but nothing seems to be working for me. Specifically, I have tried:
Adding [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] into the controller, but this makes no difference unless I provide an empty {} json object in the body. This is not what I want.
Making BodyParams nullable - again, no change.
Adding .AddControllers(opt => opt.AllowEmptyInputInBodyModelBinding = true)... again, no change.
I Implemented the solution suggested here using the attribute modification in the comment by #HappyGoLucky. Again, this did not give the desired outcome, but it did change the response to : 400 - "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true."
I tried modifying the solution in (4) to manually set context.HttpContext.Request.Body to an empty json object... but I can't figure out the syntax for this because it need to be a byte array and at that point I feel like I am way over complicating this.
How can I get the controller to use BodyParams with default values in the case that the user provides no body and no headers at all?
You can achieve that using a Minimal API.
app.MapGet("/data",
async (HttpRequest httpRequest) =>
{
var value = true;
if (Equals(httpRequest.GetTypedHeaders().ContentType, MediaTypeHeaderValue.Parse("application/json")))
{
var bodyParams = await httpRequest.ReadFromJsonAsync<BodyParams>();
if (bodyParams is not null) value = bodyParams.ValueOne;
}
var response = new {Message = "Hello", value};
return Results.Ok(response);
});
So, as there doesn't seem to be a more straightforward answer, I have currently gone with the approach number 5) from the OP, and just tweaking the code from there very slightly.
All this does is act as an action which checks the if the user has passed in any body json. If not, then it adds in an empty anonymous type. The behaviour then is to use the default True value from the BodyParams class.
The full code for the action class is:
internal class AllowMissingContentTypeForEmptyBodyConvention : Attribute, IActionModelConvention
{
public void Apply(ActionModel action)
{
action.Filters.Add(new AllowMissingContentTypeForEmptyBodyFilter());
}
private class AllowMissingContentTypeForEmptyBodyFilter : IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
if (!context.HttpContext.Request.HasJsonContentType()
&& (context.HttpContext.Request.ContentLength == default
|| context.HttpContext.Request.ContentLength == 0))
{
context.HttpContext.Request.ContentType = "application/json";
var str = new { };
//convert string to jsontype
var json = JsonConvert.SerializeObject(str);
//modified stream
var requestData = Encoding.UTF8.GetBytes(json);
context.HttpContext.Request.Body = new MemoryStream(requestData);
}
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
// Do nothing
}
}
}
Then you can add this to any of your controllers using [AllowMissingContentTypeForEmptyBodyConvention]

ASP.NET Entity Framework return JSON object of all rows inside table

I am trying to return JSON object from PostgreSQL db and currently saving to database works fine, but trying to return result returns nothing this is currently what I have for returning list from db. Keep in mind connection string is fine functionality for creating object to db works fine.
public async Task<IEnumerable<TutorialMake>> ReadTutorialMake()
{
try
{
using (var db = new TutorialContext())
{
response = HttpStatusCode.OK;
return db.TutorialMakes.ToList();
}
} catch
{
response = HttpStatusCode.BadRequest;
return null;
}
}
I've tried with returning only db.TutorialMakes without enumerable still nothings, removing try and catch returns no errors, iqueryable returns nothing and there is data inside table
Code is fine, it was just the way I configured my API I didn't return the list in API.
Because you forget to convert List result to JsonObject
Example :
public async Task<JsonResult> ReadTutorialMake()
{
try
{
using (var db = new TutorialContext())
{
response = HttpStatusCode.OK;
return Json(db.TutorialMakes.ToList()); //Convert result to JsonResult
}
} catch
{
response = HttpStatusCode.BadRequest;
return null;
}
}

Convert an api result set to a c# Object

I am calling an API to get a set of assignment data as JSON. I would like to convert that into C# model objects and display the results in my MVC view. Here is my code so far that successfully brings back the results, now I need it converted to an assignment Model (i.e I need API response.content turned into assignment).
[HttpGet]
public async Task<ViewResult> Index()
{
if (!ModelState.IsValid)
{
return View("Error");
}
HttpRequestMessage apiRequest = CreateRequestToService(HttpMethod.Get, "api/Assignment/GetAll");
HttpResponseMessage apiResponse;
Assignment assignment = new Assignment();
try
{
apiResponse = await HttpClient.SendAsync(apiRequest);
}
catch
{
return View("Error");
}
if (!apiResponse.IsSuccessStatusCode)
{
return View("Error");
}
var result = apiResponse.Content.ReadAsStringAsync();
var results = ???
return View( results);
}
I need API response.content turned into assignment
Convert the content of the response to the desired type. Lets assume it is a collection of the models
//...
var assignments = await apiResponse.Content.ReadAsAsync<List<Assignment>>();
//...

I'm not using dependency injection, but I'm getting "An error occurred when trying to create a controller of type"

I've seen lots of answers about how improper use of dependency injection can cause the error...
An error occurred when trying to create a controller of type 'FranchiseUserController'. Make sure that the controller has a parameterless public constructor.
but I am not using any dependency injection products like Ninject, Unity, etc.
Also, this error does not happen in my local development environment, but is showing up when we are testing on our QA server. Furthermore, it occurs intermittently and it occurs with several of my Web API methods. It occurs with multiple users and with multiple browsers.
I'm not sure what code to even post here. Let me know if you need more information and I will be glad to post it.
This is an ASP.NET MVC / WebAPI application using AngularJS. The error occurs when calling the Web API controller from an Angular client. The angular app is receiving a response in the Error callback with a 500 Internal Server Error with...
Data Exception Message: An error occurred when trying to create a controller of type 'FranchiseUserController'. Make sure that the controller has a parameterless public constructor.
Data Exception Type: System.InvalidOperationException
Here is the constructor from the controller that is mentioned in the error and the method that was being called.
The constructor
public FranchiseUserController()
{
_sm = new SettingManager();
_millicare_connectionString = _sm.conn_MilliCareSvcConnectionString();
_maa_connectionString = _sm.conn_MaaSvcConnectionString();
if (AppConstants.OverrideSecurityLocal && _sm.ServiceConfiguration() == ServiceConfigurationValues.LOCAL)
{
_acsUser.Name = Environment.UserName;
_acsUser.MaaUserGuid = _sm.developerAdGuid().ConvertAdGuidToMaaGuid();
_acsUser.Role = _sm.app_TestUserRole();
}
else {
ClaimsPrincipal userClaims = (ClaimsPrincipal)this.User;
_acsUser.Name = ((ClaimsIdentity)userClaims.Identity).FindFirst(MiddlewareClaimTypes.Name).Value;
_acsUser.MaaUserGuid = ((ClaimsIdentity)userClaims.Identity).FindFirst(MiddlewareClaimTypes.MaaUserGuid).Value;
_acsUser.Role = AppConstants.RoleNotAuthorized;
//Get user role
if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Maint_Option, AppConstants.Maint_Action, AppConstants.Maint_SecureValue_Approver, _sm.acs_MAAFranchiseResourceMaint()))
{
_acsUser.Role = AppConstants.RoleApprover;
}
else if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Maint_Option, AppConstants.Maint_Action, AppConstants.Maint_SecureValue_Admin, _sm.acs_MAAFranchiseResourceMaint()))
{
_acsUser.Role = AppConstants.RoleAdmin;
}
else if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Resource_Option, AppConstants.Resource_Action, AppConstants.Resource_SecureValue_Franchise, _sm.acs_MAAFranchiseResourceReports()))
{
_acsUser.Role = AppConstants.RoleFranchise;
}
}
}
...and the method
[ValidateCustomAntiForgeryToken]
[HttpPost]
public HttpResponseMessage UpdateAddress(Address_dto Value)
{
HttpResponseMessage srvresponse = new HttpResponseMessage();
if (_acsUser.Role == AppConstants.RoleAdmin || _acsUser.Role == AppConstants.RoleApprover)
{
Value.modified_user = _acsUser.Name;
srvresponse = WrapServiceCall<string>((serviceResult, responseMessage) =>
{
MilliCareSvcClient().Using(svc =>
{
serviceResult.OperationSuccessful = svc.UpdateAddress(Value);
});
});
return srvresponse;
}
else
{
var noaccessServiceResult = new ServiceResult<string>();
noaccessServiceResult.SetUnauthorizedMessage();
srvresponse.Content = new ObjectContent<ServiceResult<string>>(noaccessServiceResult, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
return srvresponse;
}
//});
}
Most likely, you have code in your controller constructor that accesses the HttpControllerContext in some way. You may be running into situations where the HttpControllerContext is not ready before the controller is created (perhaps during an application pool restart).
It is best to keep your controller constructors simple, since they may be created at any point during the lifecycle of the application. If you were using DI, I would suggest to move your complex logic into a service and don't do anything in the constructors except assign services. However, since you are not using DI, you could potentially fix this issue by moving your logic into the Initialize event of your controller, and removing the constructor entirely.
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
_sm = new SettingManager();
_millicare_connectionString = _sm.conn_MilliCareSvcConnectionString();
_maa_connectionString = _sm.conn_MaaSvcConnectionString();
if (AppConstants.OverrideSecurityLocal && _sm.ServiceConfiguration() == ServiceConfigurationValues.LOCAL)
{
_acsUser.Name = Environment.UserName;
_acsUser.MaaUserGuid = _sm.developerAdGuid().ConvertAdGuidToMaaGuid();
_acsUser.Role = _sm.app_TestUserRole();
}
else
{
ClaimsPrincipal userClaims = (ClaimsPrincipal)this.User;
_acsUser.Name = ((ClaimsIdentity)userClaims.Identity).FindFirst(MiddlewareClaimTypes.Name).Value;
_acsUser.MaaUserGuid = ((ClaimsIdentity)userClaims.Identity).FindFirst(MiddlewareClaimTypes.MaaUserGuid).Value;
_acsUser.Role = AppConstants.RoleNotAuthorized;
//Get user role
if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Maint_Option, AppConstants.Maint_Action, AppConstants.Maint_SecureValue_Approver, _sm.acs_MAAFranchiseResourceMaint()))
{
_acsUser.Role = AppConstants.RoleApprover;
}
else if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Maint_Option, AppConstants.Maint_Action, AppConstants.Maint_SecureValue_Admin, _sm.acs_MAAFranchiseResourceMaint()))
{
_acsUser.Role = AppConstants.RoleAdmin;
}
else if (ApplicationMiddleware.Security.Extensions.HasClaim(userClaims, AppConstants.Resource_Option, AppConstants.Resource_Action, AppConstants.Resource_SecureValue_Franchise, _sm.acs_MAAFranchiseResourceReports()))
{
_acsUser.Role = AppConstants.RoleFranchise;
}
}
}
NOTE: I cannot say for certain this is what is happening in your application, however you should always assume there is no HTTP Context available at the time a controller is instantiated.
On a side note, this logic looks like a cross-cutting concern. You should be doing it in a filter, not repeating it in every controller.

How to deserialize

How to deserialize Task response using Json .
public HttpResponseMessage Put(int id, ModelClass modelbject)
{
if (ModelState.IsValid && id == modelbject.modelbjectID)
{
db.Entry(modelbject).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
I want to derialize this and check the IsSuccessStatusCode in my class where i am calling this put method. How can i achieve ?
I want to derialize this and check the IsSuccessStatusCode in my class where i am calling this put method.
You don't have to "deserialize" anything. The method returns an HttpResponseMessage, which has the property you're looking for.
var result = yourController.Put(someId, someObject);
var success = result.IsSuccessStatusCode;
Perhaps the fact that this is a web application is adding some confusion to how you're picturing it. But if you have a class which directly calls this method, then what you get back is simply an HttpResponseMessage object. Which can be inspected just like any other object. No actual web layer is involved in that interaction.

Resources