The input was not valid ошибка

I am facing a weird issue and almost spent 4 hours with no luck.

I have a simple Web API which I am calling on form submit.

API-

// POST: api/Tool
[HttpPost]
public void Post([FromBody] Object value)
{
    _toolService.CreateToolDetail(Convert.ToString(value));
}

HTML-

<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>
<form name="value" action="https://localhost:44352/api/tool" method="post">
  First name:<br>
  <input type="text" id="PropertyA" name="PropertyA" value="Some value A">
  <br>
  Last name:<br>
  <input type="text" id="PropertyB" name="PropertyB" value="Some value B">
  <br><br>
  <!--<input type="file" id="Files" name="Files" multiple="multiple"/>-->
  <br><br>
  <input type="submit" value="Submit">

  </form>
</body>
</html>

When I hit the submit button I get below error-

{"":["The input was not valid."]}

Configurations in Startup class-

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSingleton<IConfiguration>(Configuration);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

This only happens for POST request. GET request works fine. Same issue when testing in Postman REST client. Any help please? Please let me know if I can provide more details.

{
  "name":"walk dog",
  "isComplete":true
}
...

        [HttpPost]
        public async Task&lt;ActionResult&lt;TodoItem&gt;&gt; Store(TodoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
        }
...

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

У меня есть этот контроллер

[AllowAnonymous]
[HttpPost("Authenticate")]
public ActionResult Authenticate([FromBody]LoginDTO Input)
{
    return Ok(Input);
}

LoginDTO это

public class LoginDTO
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }
}

Когда я использую Postman для доступа к нему, я получаю это сообщение

{
    "": [
        "The input was not valid."
    ]
}

Как я могу получить свой вклад? Не следует ли мне использовать предметы? Я попытался получить его через String Username и String Password в качестве параметров, но это тоже не сработало.

Обновлено:

Добавлен скриншот почтальона
.NET Core 2.1 API Post Controller возвращает недопустимый ввод

Перейти к ответу
Данный вопрос помечен как решенный


Ответы
3

Используйте необработанный режим в Postman и отправьте свой запрос как Json

{"Email":"","Password":""}

если вы используете PostMan, вы должны выбрать JSON (json.application) в необработанном режиме

Другие вопросы по теме

Don’t use FromBody. You’re submitting as x-www-form-urlencoded (i.e. standard HTML form post). The FromBody attribute is for JSON/XML.

You cannot handle both standard form submits and JSON/XML request bodies from the same action. If you need to request the action both ways, you’ll need two separate endpoints, one with the param decorated with FromBody and one without. There is no other way. The actual functionality of your action can be factored out into a private method that both actions can utilize, to reduce code duplication.

I just worked through a similar situation here; I was able to use the [FromBody] without any issues:

public class MyController : Controller
{
   [HttpPost]
   public async Task<IActionResult> SomeEndpoint([FromBody]Payload inPayload)
   {
   ...
   }
}

public class Payload
{
   public string SomeString { get; set; }
   public int SomeInt { get; set; }
}

The challenge I figured out was the ensure that the requests were being made with the Content-Type header set as «application/json». Using Postman my original request was returned as «The input was not valid.» Adding the Content-Type header fixed the issue for me.

Tags:

C#

Asp.Net Core Webapi

Asp.Net Core 2.0

Related

Вы где-то в коде используете вне комментариев и строковых переменных неиспользуемый в Матлабе символ. Наиболее частые примеры: нелатинские буквы, восклицательный и вопросительный знаки, двоеточие вместо троеточия, двойные кавычки.

Когда матлаб ругается, он пишет что-то типа

??? Error: File: new_analysis_26092011.m Line: 3 Column: 85
Unexpected MATLAB operator.

Приведите ту строчку, на которую ругается матлаб, станет окончательно понятно.

Здравствуйте. Такая же проблема)) Дана такая вот простенькая лаба, создал функцию принадлежности, сохранил ее. Создал файл, дошёл до слов

Затем создадим в той же папке m-файл, загрузим наш fis-файл (в нем только одна входная
переменная):
fis = readfis(’money.fis’);

В начале файл сохранял как kotel, открыл заново созданный м-файл, прописываю

fis = readfis(’kotel.fis’)

Выдаёт то же,что и у топикстартера:

>> fis = readfis(’kotel.fis’);
??? fis = readfis(’kotel.fis’);
|
Error: The input character is not valid in MATLAB statements or
expressions.

.
Начал гуглить, увидел эту тему. Ещё подумал,что прочитал фразу в методе

На предложение сохра-
нить (Save) результат работы нужно согласиться и сохранить файл в своей папке под разумным
англоязычным именем
, например money.fis.

Понял,что первая мысль была бредом,но чем чёрт не шутит назвал файл не kotel, а money. Как вы поняли, ничего не изменилось

>> fis = readfis(’money.fis’);
??? fis = readfis(’money.fis’);
|
Error: The input character is not valid in MATLAB statements or
expressions.

В чём может быть проблема?) Во вложенном архиве файл с функцией принадлежности и метода.

While calling an apiController method from Postman I encountered a problem.

the method with params mentioned in Postman client call below method

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Register([FromBody]UserDto userDto)
    {
        // map dto to entity
        //var user = _mapper.Map<User>(userDto);
        return Ok(new
        {
            userDto
        });

        //try
        //{
        //    // save 
        //    _userService.Create(user, userDto.Password);
        //    return Ok();
        //}
        //catch (AppException ex)
        //{
        //    // return error message if there was an exception
        //    return BadRequest(new { message = ex.Message });
        //}
    }

which maps the UserDto..

public class UserDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

but instead I get the error below :

Postman Client

Понравилась статья? Поделить с друзьями:
  • The i of the dragon выдает ошибку
  • The hunter не запускается ошибка
  • The hunter call of the wild ошибка при установке
  • The hunter call of the wild ошибка при запуске
  • The hunter call of the wild ошибка error report