[英]WebApi - The request contains an entity body but no Content-Type header
[英]ASPNET 5: How to receive request parameter as raw content no matter what the Content-Type header is set to?
我正在構建一個API,客戶端可以向我發送大量數據,然后將其保存到某個地方以便以后檢索。 我不在乎內容類型是什么。 我只想每次都獲取原始數據,無論他們將Content-Type設置為什么。 我知道這可以通過訪問Request對象在舊版本的ASPNET中實現,但這似乎不可能與ASPNET 5,我也不想這樣做,因為它會使單元測試不可能(請求不是依賴注入)。
我已經看到了一些關於IInputFormatter和IOutputFormatter接口的提及,但這些接口似乎附加到特定的Content-Type。 我想我正在尋找更像[FromBody]屬性的東西,但這給了我原始輸出。 像[RawBody]這樣的東西。 我做了很多搜索,似乎找不到任何簡單的解決方案。
您可以創建CustomAttribute
並使用StreamReader
讀取Request.InputStream
保存流數據,然后將InputStream位置重置為0 httpContext.Request.InputStream.Position = 0;
我在Custom AuthorizeAttribute
使用它,但您可以使用Custom ActionFilter
並使用來自filterContext
Request
,您可以谷歌搜索“MVC c#中的自定義屬性”,您也可以在ActionResult
執行此操作。
如果您仍在尋找解決方案來獲取Request Object,那么這就是解決方案
創建MessageHandler
public class MessageHandler1 : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpContextWrapper context = (HttpContextWrapper)request.Properties.ElementAt(0).Value;
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
return response;
}
}
添加WebApiConfig的條目
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MessageHandlers.Add(new MessageHandler1());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
現在,您可以訪問MessageHandler1
行請求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.