Search code examples
asp.netwpfrestautorest

WebApi and Swagger


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


Solution

  • 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.