0

I am new to web development using Web API and I'm having some issues dealing with authentication using a custom message handler - specifically calling the Web API methods from a C# WPF application using HttpClient.

I've implemented authentication using a custom DelegatingHandler as in the TokenInspector class example given here (minus the HTTPS stuff). From the post I understand this moves authentication higher up in the request pipeline than having Action Filters as in this popular post.

I can successfully call my secured methods using an ajax call like the following (where _key is the security token):

$.ajax({
    url: _api + '/Item',
    beforeSend: function(request) {
                    request.setRequestHeader("X-Token", _key);
                },
    type: 'GET',
    dataType: 'json',
    success: fnSuccessResult,
    error: function (xhr, status, error) {
               alert(xhr.status + ' ' + status + ' ' + error);
           }
});

I am in the process of writing a test harness for my Web API in C# - how do I handle this type of authentication in C# using HttpClient?

1 Answer 1

1

Try this:

var client = new HttpClient();
var request = new HttpRequestMessage();
request.Headers.Add("X-Token", "token");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;
client.SendAsync(request);
Sign up to request clarification or add additional context in comments.

5 Comments

I am getting an "Internal Server Error" response, same as all my other attempts thus far. Is there a way to get the server to send more details on the error? I've put a breakpoint in the SendAsync method of my custom DelegatingHandler class, but it doesn't get hit.
How does your Handler look like? How did you register it?
Your code works as expected. There must be an error not related to your MessageHandler implementation.
I've added another method to my Controller to test - it works with your solution. I then changed the original controller method name after which it now works, strange... Thanks for your help.
I've added a similar follow-up question regarding problems I have posting data using this approach.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.