2

I got three Web API project.

They deployed at

  1. api:http://api.domain.com
  2. mobileApi:http://mobile.api.domain.com
  3. logApi:http://log.api.domain.com

I want do this: When an error occured in other project,record the error by calling a controller in logApi.I have read http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

So I write this class for helping send request to a Web API controller

public class WebApiRequest
{
    public static T Get<T>(string url, object param = null, object header = null, Func<HttpResponseMessage, T> converter = null)
    {
        HttpClient client = GetClient(header);
        url = UrlHelper.BuildUrl(url, param);
        HttpResponseMessage response = client.GetAsync(url).Result;
        response.EnsureSuccessStatusCode();
        return converter != null ? converter(response) : DefaultConverter<T>(response);
    }

    public static T Post<T>(string url, object param = null, object header = null, Func<HttpResponseMessage, T> converter = null)
    {
        HttpClient client = GetClient(header);
        var content = new FormUrlEncodedContent(
            Tool.AnonymousObjectToDictionary(param).Where(i => i.Value != null).ToDictionary(i => i.Key, i => i.Value.ToString()));
        HttpResponseMessage response = client.PostAsync(url, content).Result;
        response.EnsureSuccessStatusCode();
        return converter != null ? converter(response) : DefaultConverter<T>(response);
    }

    public static T Put<T>(string url, object param = null, object header = null, Func<HttpResponseMessage, T> converter = null)
    {
        HttpClient client = GetClient(header);
        var content = new FormUrlEncodedContent(
            Tool.AnonymousObjectToDictionary(param).Where(i => i.Value != null).ToDictionary(i => i.Key, i => i.Value.ToString()));
        HttpResponseMessage response = client.PutAsync(url, content).Result;
        response.EnsureSuccessStatusCode();
        return converter != null ? converter(response) : DefaultConverter<T>(response);
    }

    public static T Delete<T>(string url, object param = null, object header = null, Func<HttpResponseMessage, T> converter = null)
    {
        HttpClient client = GetClient(header);
        url = UrlHelper.BuildUrl(url, param);
        HttpResponseMessage response = client.DeleteAsync(url).Result;
        response.EnsureSuccessStatusCode();
        return converter != null ? converter(response) : DefaultConverter<T>(response);
    }

    private static T DefaultConverter<T>(HttpResponseMessage response)
    {
        var formatters = new List<MediaTypeFormatter> {
            new JsonMediaTypeFormatter(),
            new XmlMediaTypeFormatter()
        };
        var result = response.Content.ReadAsAsync<T>(formatters).Result;
        return result;
    }

    public static string StringConverter(HttpResponseMessage response)
    {
        return response.Content.ReadAsStringAsync().Result;
    }

    private static HttpClient GetClient(object header)
    {
        HttpClient client = HttpClientFactory.Create(new DecompressionHandler());
        var headers = Tool.AnonymousObjectToDictionary(header);
        foreach (var h in headers.Where(h=>h.Value!=null)) {
            client.DefaultRequestHeaders.Add(h.Key, h.Value.ToString());
        }
        return client;
    }
}

In a test project,It works perfect.

But when I use it in a Web API project,things become very strange.

    WebApiRequest.Post<ReturnModel<int>>(logUrl, new {
        Source = "{" + source + "}",
        context.Exception.Message,
        context.Exception.StackTrace,
        ExceptionType = context.Exception.GetType().FullName,
        PriorityLevel = 3,
        AddTime = DateTime.Now,
        ProjectType = (short)ProjectType.WebApi,
    }, request.Headers);

The code seems OK,but actually the HttpClient is not request the url I give to it!!

Anyone can help, I appreciate it and thanks a lot.

6
  • Could it be that the API you're trying to call is on the same machine? In this case it might be needed to add the URL to your windows HOST file. Otherwise could you please give a little more context to where your API's are running (same machine/different) and what the HttpClient is requesting and what you expect it to request?
    – Jos Vinke
    Mar 12, 2013 at 8:20
  • Thank you for comment.They deployed at same machine.But even I run a localhost Web API project to request log.api.domain.com. It's still not working.I expect it to request log.api.domain.com/errorlog .But actually it request localhost:4310/errorlog
    – Neo Zhou
    Mar 12, 2013 at 9:16
  • Did you already take a look at your Hosts file? techfleece.com/2011/08/15/…
    – Jos Vinke
    Mar 12, 2013 at 9:42
  • Yes,whether I add the rule or not ,still not working
    – Neo Zhou
    Mar 14, 2013 at 1:13
  • It's kinda hard to help you out with this code, where does the URL parameter come from? Could it be that somewhere in the code you get the URL from the HttpContext.Current.Request.Url and that this is not pointing at the URL you expect it to?
    – Jos Vinke
    Mar 14, 2013 at 9:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.