Click here to Skip to main content
15,891,951 members
Home / Discussions / Web Development
   

Web Development

 
GeneralRe: Anyone has chrome debugging issue today.... Pin
Super Lloyd18-Jun-19 14:20
Super Lloyd18-Jun-19 14:20 
Questionjquery chatbot code example for static answers Pin
byka17-Jun-19 8:40
byka17-Jun-19 8:40 
AnswerRe: jquery chatbot code example for static answers Pin
Mycroft Holmes17-Jun-19 12:15
professionalMycroft Holmes17-Jun-19 12:15 
Questiondoes anyone here use ELMAH? Pin
#realJSOP14-Jun-19 9:08
mve#realJSOP14-Jun-19 9:08 
QuestionDraw 3*3 Rubik’s cube Pin
Member 1449931913-Jun-19 6:53
Member 1449931913-Jun-19 6:53 
AnswerRe: Draw 3*3 Rubik’s cube Pin
#realJSOP13-Jun-19 7:48
mve#realJSOP13-Jun-19 7:48 
AnswerRe: Draw 3*3 Rubik’s cube Pin
ZurdoDev17-Jun-19 11:33
professionalZurdoDev17-Jun-19 11:33 
QuestionProblems Calling Asp.Net WebAPI 2 Pin
Kevin Marois11-Jun-19 12:07
professionalKevin Marois11-Jun-19 12: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 0:45
mveRichard Deeming12-Jun-19 0:45 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 4:02
professionalKevin Marois12-Jun-19 4:02 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Richard Deeming12-Jun-19 4:25
mveRichard Deeming12-Jun-19 4:25 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 5:26
professionalKevin Marois12-Jun-19 5:26 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Kevin Marois12-Jun-19 6:34
professionalKevin Marois12-Jun-19 6:34 
GeneralRe: Problems Calling Asp.Net WebAPI 2 Pin
Richard Deeming12-Jun-19 8:10
mveRichard Deeming12-Jun-19 8:10 
QuestionEliminating External (Commercial) References/Creating my own design/Stylesheets Pin
Member 120802018-Jun-19 6:23
Member 120802018-Jun-19 6:23 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
Afzaal Ahmad Zeeshan8-Jun-19 10:18
professionalAfzaal Ahmad Zeeshan8-Jun-19 10:18 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
jamieereynoldss9-Jun-19 23:51
jamieereynoldss9-Jun-19 23:51 
AnswerRe: Eliminating External (Commercial) References/Creating my own design/Stylesheets Pin
#realJSOP10-Jun-19 5:08
mve#realJSOP10-Jun-19 5:08 
QuestionHow to learn python numpy library easily, which functions are important Pin
Member 144829305-Jun-19 22:54
Member 144829305-Jun-19 22:54 
AnswerRe: How to learn python numpy library easily, which functions are important Pin
User 41802546-Jun-19 3:56
User 41802546-Jun-19 3:56 
SuggestionRe: How to learn python numpy library easily, which functions are important Pin
Richard Deeming6-Jun-19 4:38
mveRichard Deeming6-Jun-19 4:38 
GeneralRe: How to learn python numpy library easily, which functions are important Pin
User 41802546-Jun-19 6:05
User 41802546-Jun-19 6:05 
QuestionPass Guid To Controller Pin
Kevin Marois4-Jun-19 8:37
professionalKevin Marois4-Jun-19 8:37 
AnswerRe: Pass Guid To Controller Pin
Richard Deeming5-Jun-19 12:26
mveRichard Deeming5-Jun-19 12:26 
GeneralRe: Pass Guid To Controller Pin
Kevin Marois7-Jun-19 8:03
professionalKevin Marois7-Jun-19 8:03 

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.