locked
Call WebAPI with webform or MVC5 RRS feed

  • Question

  • User729207731 posted

    I have sample web api like this.

    List<Movie> movies = new List<Movie> {
            new Movie{ ID = 1, Title = "Taken", Genre = "Action", ReleaseDate = new DateTime(2008,9,26)},
            new Movie{ ID = 2, Title = "Django Unchained", Genre = "Western", ReleaseDate = new DateTime(2013,1,18)},
            new Movie{ ID = 3, Title = "Cars", Genre = "Animation", ReleaseDate = new DateTime(2006,7,28)},
            new Movie{ ID = 4, Title = "The Hangover", Genre = "Comedy", ReleaseDate = new DateTime(2009,6,12)},
            new Movie{ ID = 5, Title = "The Woman in Black", Genre = "Horror", ReleaseDate = new DateTime(2012,2,10)}
        };
    
        // GET api/<controller>
     [Authorize] public IEnumerable<Movie> Get() { return movies; } // GET api/<controller>/5
     [Authorize] public Movie Get(int id) { return movies.SingleOrDefault(m => m.ID == id); } // POST api/<controller>
     [Authorize] public void Post([FromBody]Movie movie) { movies.Add(movie); // Save changes } // PUT api/<controller>/5
     [Authorize] public void Put(int id, [FromBody]Movie movie) { Movie existingMovie = movies.SingleOrDefault(m => m.ID == id); existingMovie.Title = movie.Title; existingMovie.Genre = movie.Genre; existingMovie.ReleaseDate = movie.ReleaseDate; // Save changes } // DELETE api/<controller>/5
     [Authorize] public void Delete(int id) { movies.Remove(movies.SingleOrDefault(m => m.ID == id)); // Save changes }

    and token authentication

      static Startup()
            {
                PublicClientId = "self";
    
                UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
    
                OAuthOptions = new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/Token"),
                    Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                    AllowInsecureHttp = true
                };
            }

    and client call 

    <script>
            $(function () {
                $('#btn-all').on('click', function () {
                    $.get('/api/movies', function (data) {
                        $('#result').empty();
                        $.each(data, function (i, v) {
                            $('#result').html($('#result').html() + v.Title + '<br />');
                        });
                    }, 'json');
                });
                $('#btn').on('click', function () {
                    $.get('/api/movies/' + $('#MovieId').val(), function (data) {
                        $('#result').empty()
                        $('#result').html(data.Title + 
                            '<br />' + data.Genre + 
                            '<br />' + data.ReleaseDate);
                    }, 'json');
                });
                $('#btn-delete').on('click', function () {
                    $.ajax({
                        type: 'Delete',
                        url: '/api/movies?id=' + $('#MovieId').val()
                    });
                });
            });
        </script>

    but this does not work, i miss parameters token, how to call with token, thanks.

    Monday, May 29, 2017 9:23 AM

Answers

  • User1879451342 posted

    If you have a web page, then you might create HttpClient class and call via an action:

    //Web Form:
     protected void Button1_Click(object sender, EventArgs e)
            {
                 callClient logClient = new CallHttpClient();         
            }
    
    //custom class:
    
     public void CallHttpClient()
    {
    private HttpClient _client;
    _client = new HttpClient();
    _client.BaseAddress = new Uri(mspBaseAddress);
    _client.Timeout = TimeSpan.FromMilliseconds(mspTimeoutInterval);
    _client.DefaultRequestHeaders.Add("Connection", "close");
    _client.DefaultRequestHeaders.Clear();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    var response = new HttpResponseMessage();
    var cts = new System.Threading.CancellationTokenSource();
    
    using (_client)
    {
    response = _client.PostAsync(new Uri(mspEndpointUrl), new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"), cts.Token).Result;
    
    if (!response.IsSuccessStatusCode)
    {
        throw new Exception(response.StatusCode.ToString());
    }
    }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 1, 2017 8:25 PM

All replies

  • User1967761114 posted

    Hi hoitm,

    According to you description, I think you have to understand these points.

    (1) How to get token from Web API?

    The user input username and password , then client post them to Web API server for authentication, if  authentication succeeds, then  Web API will return the token.

    (2) How to invoke Web API with token?

    After get the token, client could store the token in cookie or session storage, when client send a request to the Web API server, the token could be a header or a parameter in request.

    For more details about this issue, you could refer to the following link:

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Tuesday, May 30, 2017 3:29 AM
  • User1879451342 posted

    If you have a web page, then you might create HttpClient class and call via an action:

    //Web Form:
     protected void Button1_Click(object sender, EventArgs e)
            {
                 callClient logClient = new CallHttpClient();         
            }
    
    //custom class:
    
     public void CallHttpClient()
    {
    private HttpClient _client;
    _client = new HttpClient();
    _client.BaseAddress = new Uri(mspBaseAddress);
    _client.Timeout = TimeSpan.FromMilliseconds(mspTimeoutInterval);
    _client.DefaultRequestHeaders.Add("Connection", "close");
    _client.DefaultRequestHeaders.Clear();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    var response = new HttpResponseMessage();
    var cts = new System.Threading.CancellationTokenSource();
    
    using (_client)
    {
    response = _client.PostAsync(new Uri(mspEndpointUrl), new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"), cts.Token).Result;
    
    if (!response.IsSuccessStatusCode)
    {
        throw new Exception(response.StatusCode.ToString());
    }
    }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 1, 2017 8:25 PM