Click here to Skip to main content
14,388,839 members

Web Development

 
Questiondoes anyone here use ELMAH? Pin
#realJSOP14-Jun-19 10:08
mve#realJSOP14-Jun-19 10:08 
QuestionDraw 3*3 Rubik’s cube Pin
Member 1449931913-Jun-19 7:53
MemberMember 1449931913-Jun-19 7:53 
AnswerRe: Draw 3*3 Rubik’s cube Pin
#realJSOP13-Jun-19 8:48
mve#realJSOP13-Jun-19 8:48 
AnswerRe: Draw 3*3 Rubik’s cube Pin
ZurdoDev17-Jun-19 12:33
professionalZurdoDev17-Jun-19 12:33 
QuestionProblems Calling Asp.Net WebAPI 2 Pin
Kevin Marois11-Jun-19 13:07
professionalKevin Marois11-Jun-19 13:07 
A bit long but I'm really stuck here.

I've posted about this before, but I stil can't figure out what's wrong, so I"m going to extend my question with a lot more code.

I'm working on a WPF app that calls an Asp.net WebAPi. I'm having trouble calling Web API methods. In some cases, the API call succeeds and in some cases it fails. The issue seems to be the TYPE of params being passed.

I could really use someone with a lot more insight than me to help. Google searches lead me all over the place and I"m really stuck.

For example, this method works fine
[HttpPost]
public Response<Guid> AddRuleDefinition(RuleDefinitionEntity entity)
{
    var response = new Response<Guid>();

    try
    {
        IRulesBL bl = GetBL();
        response.Data = bl.AddRuleDefinition(entity);
    }
    catch (Exception e)
    {
        response.Exception = e;
    }

    return response;
}
This only works if I pass the Guid as a string:
[HttpDelete]
public Response DeleteRuleDefinition([FromUri] string id)
{
    var response = new Response();

    try
    {
        IRulesBL bl = GetBL();
        bl.DeleteRuleDefinition(new Guid(id));  // CONVERT THE STRING BACK TO A GUID
    }
    catch (Exception e)
    {
        response.Exception = e;
    }

    return response;
}
This works, but the results list is null. The 'trigger' parameter is there:
[HttpPost]
public Response<List<string>> ExecuteRuleGroup(List<AssayResultEntity> results, string trigger)
{
    var response = new Response<List<string>>();

    try
    {
        IRulesBL bl = GetBL();
        response.Data = bl.ExecuteRuleGroup(trigger, results);
    }
    catch (Exception e)
    {
        response.Exception = e;
    }

    return response;
}

I call the methods from the client using an wrapper class I call WebAPIExecutor.
public class WebAPIExecutor
{
    private RestClient client;

<pre>
private RestRequest request;

public string ServerAddress { get; private set; }

public string URL { get; private set; }

public WebAPIExecutor(CredentialsEntity credentials, string ipAddress, string controller, Method method = Method.POST)
{
    ServerAddress = string.Format("<a href="http://{0}/api">http://{0}/api</a>", ipAddress);

    client = new RestClient(ServerAddress);

    client.AddHandler("text/plain", new JsonDeserializer());

    request = new RestRequest(controller, method)
    {
        RequestFormat = DataFormat.Json
    };
}

public void AddParameter(object value, string name = "")
{
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }

    Type type = value.GetType();
    bool isPrimitive = type.IsPrimitive;

    if (isPrimitive || type == typeof(string) || type == typeof(decimal))
    {
        if (string.IsNullOrEmpty(name) && request.Method == Method.GET)
        {
            throw new ArgumentNullException("Parameter 'Name' cannot be empty for Get requests");
        }

        request.AddParameter(name, value);
    }
    else
    {
        request.AddBody(value);
    }
}

public async Task<T> ExecuteAsync<T>() where T : new()

{

URL = client.BaseUrl + request.Resource;

IRestResponse<t> restResponse = await client.ExecuteTaskAsync<t>(request, new CancellationToken());

var result = (T)restResponse.Data;

if (!string.IsNullOrEmpty(restResponse.ErrorMessage))
{
throw new Exception(restResponse.ErrorMessage);
}
else
{
if ((int)restResponse.StatusCode >= 299)
{
string message = string.Format("An error occured calling the WebAPI. {0} The status code is '{1}'. {2} The error message is {3}",
Environment.NewLine, restResponse.StatusCode, Environment.NewLine, restResponse.Content);
throw new Exception(message);
}
}

return result;
}

public async Task ExecuteAsync()
{
URL = client.BaseUrl + request.Resource;

IRestResponse result = null;

try
{
result = await client.ExecuteTaskAsync(request);

int resultCode = (int)result.StatusCode;

if (resultCode > 299)
{
string message = string.Format("An error occured calling the WebAPI. {0} The status code is '{1}'. {2} The error message is {3}",
Environment.NewLine, resultCode, Environment.NewLine, result.Content);

throw new Exception(message);
}
}
catch (Exception e)
{
throw e;
}
}
}



Then I created a proxy which has many methods that all look like this:
public async Task<Response<Guid>> AddRuleDefinitionAsync(RuleDefinitionEntity entity)
{
    var webAPIExecutor = new WebAPIExecutor(Credentials, ServerUrl, "/Rules/AddRuleDefinition/", Method.POST);
    webAPIExecutor.AddParameter(entity, "entity");
    return await webAPIExecutor.ExecuteAsync<Response<Guid>>();
}

Here's my WebAPIConfig:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional });
    }
}
Global.Asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.MessageHandlers.Add(new APIKeyHandler());
        GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthHandler());

        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.

AnswerRe: Problems Calling Asp.Net WebAPI 2 Pin
Richard Deeming12-Jun-19 1:45
mveRichard Deeming12-Jun-19 1:45 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 5:02
professionalKevin Marois12-Jun-19 5:02 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Richard Deeming12-Jun-19 5:25
mveRichard Deeming12-Jun-19 5:25 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 6:26
professionalKevin Marois12-Jun-19 6:26 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 7:34
professionalKevin Marois12-Jun-19 7:34 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Richard Deeming12-Jun-19 9:10
mveRichard Deeming12-Jun-19 9:10 
QuestionEliminating External (Commercial) References/Creating my own design/Stylesheets Pin
Member 120802018-Jun-19 7:23
MemberMember 120802018-Jun-19 7:23 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
Afzaal Ahmad Zeeshan8-Jun-19 11:18
mvaAfzaal Ahmad Zeeshan8-Jun-19 11:18 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
jamieereynoldss10-Jun-19 0:51
Memberjamieereynoldss10-Jun-19 0:51 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
#realJSOP10-Jun-19 6:08
mve#realJSOP10-Jun-19 6:08 
QuestionHow to learn python numpy library easily, which functions are important Pin
Member 144829305-Jun-19 23:54
MemberMember 144829305-Jun-19 23:54 
AnswerRe: How to learn python numpy library easily, which functions are important Pin
Vinod Jangle6-Jun-19 4:56
MemberVinod Jangle6-Jun-19 4:56 
SuggestionRe: How to learn python numpy library easily, which functions are important Pin
Richard Deeming6-Jun-19 5:38
mveRichard Deeming6-Jun-19 5:38 
GeneralRe: How to learn python numpy library easily, which functions are important Pin
Vinod Jangle6-Jun-19 7:05
MemberVinod Jangle6-Jun-19 7:05 
GeneralMessage Closed Pin
10-Jun-19 0:49
Memberjamieereynoldss10-Jun-19 0:49 
AnswerMessage Closed Pin
15-Jun-19 4:55
MemberRahul Khot15-Jun-19 4:55 
QuestionPass Guid To Controller Pin
Kevin Marois4-Jun-19 9:37
professionalKevin Marois4-Jun-19 9:37 
AnswerRe: Pass Guid To Controller Pin
Richard Deeming5-Jun-19 13:26
mveRichard Deeming5-Jun-19 13:26 
GeneralRe: Pass Guid To Controller Pin
Kevin Marois7-Jun-19 9:03
professionalKevin Marois7-Jun-19 9:03 
GeneralRe: Pass Guid To Controller Pin
Kevin Marois11-Jun-19 13:08
professionalKevin Marois11-Jun-19 13:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.