Параметр, переданный из Angular в C #, не является ожидаемым типом - PullRequest
0 голосов
/ 07 февраля 2019

Я пытаюсь передать параметр через POST из Angular-клиента в ac # backend.Я не могу понять, почему первый подход терпит неудачу, когда второй работает.В обоих случаях разве результат не передается в c #, преобразованный обратно в его тип?

ANGULAR

passwordResetRequest(email: string): Observable<string> {
    console.log('auth svc: ' + email)
    return this.http.post<string>("api/auth/forgotPassword", {email:email} ).pipe(
        catchError(this.handleError('error sending pwd reset request','error receiving response'))
    );
}

C # конечная точка FAILS

[HttpPost]
[AllowAnonymous]
[Route("forgotPassword")]
public async Task<IActionResult> ForgotPassword(JsonResult r){}//500 server error

//FAILS also
public async Task<IActionResult> ForgotPassword([FromBody] string r){}//r=null

C # конечная точка WORKS

[HttpPost]
[AllowAnonymous]
[Route("forgotPassword")]
public async Task<IActionResult> ForgotPassword([FromBody] MyClass r)

public class MyClass
{
    public string email { get; set; }
}

1 Ответ

0 голосов
/ 07 февраля 2019

Как я помню, ASP.NET WebAPI не может обрабатывать text/plain тип мультимедиа, поэтому, если вы отправляете только строку, ваша конечная точка получает пустую строку, вы можете попытаться установить другой заголовок Content-Type в запросе,или, если вы хотите добавить поддержку к типу контента text/plain, вы можете следовать этому руководству .

public class PlainTextMediaTypeFormatter : MediaTypeFormatter
{
    public PlainTextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var source = new TaskCompletionSource<object>();

        try
        {
            using (var memoryStream = new MemoryStream())
            {
                readStream.CopyTo(memoryStream);
                var text = Encoding.UTF8.GetString(memoryStream.ToArray());
                source.SetResult(text);
            }
        }
        catch (Exception e)
        {
            source.SetException(e);
        }
        return source.Task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken)
    {
        var bytes = Encoding.UTF8.GetBytes(value.ToString());
        return writeStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return type == typeof(string);
    }
}

Затем его можно добавить в коллекцию config.Formatters:

public static class WebApiConfig
{
  public static void Register(HttpConfiguration http)
  {
    http.Formatters.Add(new PlainTextMediaTypeFormatter());
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...