【问题标题】:MVC WebAPI Call Works Once and Only OnceMVC WebAPI 调用一次且仅一次
【发布时间】:2023-01-20 01:33:02
【问题描述】:

我有一个部署为 Azure Web 应用程序的 WebAPI 它是 .net Framework 4.6.2。我可以调用它一次(来自各种来源,包括我的 JavaScript 代码和 Postman),但第二次调用它时,我收到以下错误:

{ "message": "请求包含实体主体但没有 Content-Type 头。推断的媒体类型 此资源不支持 'application/octet-stream'。", “ExceptionMessage”:“没有 MediaTypeFormatter 可用于从媒体内容中读取‘ImportSourceLineActionRequest’类型的对象 输入“应用程序/八位字节流”。 "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException", “StackTrace”:“在 System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent 内容、类型类型、IEnumerable 1 格式化程序、IFormatterLogger formatterLogger, CancellationToken cancellationToken) 在 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage 请求、类型类型、IEnumerable`1 格式化程序、IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }

一些注意事项:

  • Content-Type 在 Postman 中设置为“application/json”
  • Content-Type 在我的 JavaScript 中设置为“application/json”

那么......为什么我的网络服务突然认为我正在发送应用程序/八位字节流?

此外,重新启动 Web 应用程序可以解决问题……再一次。

进行调用的 Javascript 代码:

const resp = await fetch(callUrl, {
    method: 'POST',
    body: bodyOjbectStr,
    headers:
    {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
});

被调用的 API 方法

[HttpPost]
public void DoSomeWork(DoSomeWorkRequestRequest request)
{
    // Do various things
}

WebApiConfig.cs (sn-p of)

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // config.Filters.Add(new RequireHttpsAttribute());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",StringComparison.InvariantCultureIgnoreCase,true,"application/json"));
        }
    }

感激地接受任何帮助。

DS

【问题讨论】:

  • bodyOjbectStr 是字符串还是对象?
  • @MohitGanorkar 对象的 JSON 化字符串。所以,字符串。

标签: c# asp.net-web-api azure-web-app-service


【解决方案1】:

为了完整起见,这个问题得到了解决。结果证明是我们使用的 2FA 有问题。不知道为什么它曾经工作一次而第二次失败,但是当 IT 对 2FA 进行一些调整时,一切都奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多