Consume RESTful Web service in ASP .NET


I have a situation, I must consume a RESTful Web service with OAuth2 authentication and my application is developed on ASP.NET.

What can I use to consume this service? How should I create the client using libraries like OWIN or others?

asked by 04.02.2016 в 18:02

2 answers


To consume a REST service from .NET you must use the class HttpClient . In this link you have an example how to use it (the code C# would be something like this)

using (var client = new HttpClient())
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);

Regarding authentication OAuth you could use the library AsyncOAuth and then change the first line of the previous code to configure HttpClient in order to manage authentication with this library:

using (var client = new HttpClient(new OAuthMessageHandler(
    new AccessToken("accessToken", "accessTokenSecret"))))

According to the documentation of this library, you must also put the following code in the Application_Start to be able to perform cryptographic calculations of HASH

OAuthUtility.ComputeHash = (key, buffer) => { 
    using (var hmac = new HMACSHA1(key)) 
        return hmac.ComputeHash(buffer); 
answered by 04.02.2016 в 18:29

If the server exposes webapi service marked with the [Authorize] attribute, the first step will be to obtain a token that allows access to the services.

I would recommend you take a look at this article

Secure a Web API with individual accounts and the Local login in ASP.NET Web API 2.2

As you will understand from the webapi an endpoint is exposed as /Token is to which you must make the first call to get the token that you should send to the other services when you invoke them

From you could work in two ways

important as you define the token in the header

var headers = {};  
if (token) {  
    headers.Authorization = 'Bearer ' + token;  

        type: 'GET',  
        url: '/api/values',  
        headers: headers  
}).done(function (data) {  

As you will understand, a previous step is required to obtain the token that will give you access to the services.

answered by 04.02.2016 в 18:26