我正在尝试通过POST将参数从Angular客户端传递到c#后端。我无法弄清楚为什么第二种方法失败时第一种方法失败了。在这两种情况下,传递给c#的结果都不会转换回其类型吗?
英语
mixer.quit()
C#端点失败
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#端点工作
[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
答案 0 :(得分:0)
我记得,ASP.NET WebAPI无法处理text/plain
媒体类型,因此,如果仅发送该字符串,则端点将获得一个空字符串,则可以尝试在该字符串上设置其他Content-Type标头请求,或者,如果您想为text/plain
内容类型添加支持,则可以遵循this tutorial.
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());
}
}