Неверный запрос, когда я указываю на свой URL http://localhost:59185/api/values ... в надежде получить токен доступа вместо этого, чтобы получить ошибку - PullRequest
1 голос
/ 10 июня 2019

У меня есть проект веб-API в visual studio, где я перенаправляю веб-URL на мой локальный хост, у меня есть класс модели и контроллер значений, и в настоящее время я пытаюсь получить ответ от моего API.

Изображение почтальона (как почтальон взял учетные данные) Нажмите здесь

Во время выполнения этого проекта я сталкиваюсь с сообщением об ошибке на своем URL -> http://localhost:59185/api/values

Сообщение об ошибке:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{"error":"invalid_request","error_description":"grant_type is required for issuance"}
</string>

Это говорит мне, что grant_type требуется для выдачи, но я определил его, мой класс Valuescontroller ..

using APICredential.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace APICredential.Controllers
{
    [RoutePrefix("api")]
    public class ValuesController : ApiController
    {

        [HttpGet, Route("values")]
        public async Task<string> Post()
        {
            Credentials cred = new Credentials()
            {

                username = "admin@encompass:BE11200822",
                password = "S*******",
                grant_type = "password", //Gran_type Identified here
                client_id = "gpq4sdh",
                client_secret = "secret",
                scope = "lp"
            };

            try {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

                    HttpRequestMessage request = new HttpRequestMessage
                    (HttpMethod.Post, "v1/token")
                    {
                        Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/x-www-form-urlencoded")
                    };

                    HttpResponseMessage response = await client.SendAsync(request);

                    //for now, see what response gets you and adjust your code to return the object you need, if the api is returning a serialized json string.. then we can return a string here... like so

                    string result = await response.Content.ReadAsStringAsync();

                    return result;

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        [HttpGet, Route("values/{id}")]
        public string Get(int id)
        {
            return "Nice! At least we got this one working, Fay... the Id value you entered is: " + id.ToString();
        }

1 Ответ

0 голосов
/ 10 июня 2019

Если посмотреть на скриншот вашего Почтальона, похоже, что вы неправильно передаете контент в API.Это должно быть что-то вроде этого:

namespace APICredential.Controllers
{
    [RoutePrefix("api")]
    public class ValuesController : ApiController
    {

        [HttpGet, Route("values")]
        public async Task<string> Post()
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");



                var parameters = new Dictionary<string, string>()
                {
                    {"username", "admin@encompass:BE11200822"},
                    {"password ", "S*******"},
                    {"grant_type", "password"}, //Gran_type Identified here
                    {"client_id", "gpq4sdh"},
                    {"client_secret", "secret"},
                    {"scope", "lp"}
                };

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v1/token")
                {
                    Content = new FormUrlEncodedContent(parameters)
                };

                HttpResponseMessage response = await client.SendAsync(request);

                string result = await response.Content.ReadAsStringAsync();

                return result;
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...