10

我對MVC相當陌生,所以我希望有解決我的問題的方法。我正在使用第三方硬件與我的MVC Web API進行通信。硬件以JSON格式發送請求,我可以很好地提取這些請求。但是,由於衝突,我正在將這些請求的參數更改爲綁定模型對象。覆蓋MVC POST請求的內容標頭

E.G.

 Public Function POSTRequest(Action As String, Stamp As String) As HttpResponseMessage 
      ... 
     End Function 

     Public Function POSTRequest(Action As String, OpStamp As String) As HttpResponseMessage 
      ... 
     End Function 

所以這兩種方法共享相同的呼叫卡,因此它們都不能存在於同一個控制器中。

由於這個原因,我創建了模型綁定對象來代替這些參數。問題是,一旦我這樣做,Web API就會抱怨說「Content-Type」沒有被定義。看着它,第三方硬件不會向請求發送內容類型。在網絡上看,我發現這導致瀏覽器將其視爲內容類型「application/octet-stream」。這不能將其轉換爲定義爲參數的綁定對象。

我們無法控制第三方硬件,因此我們無法定義這些請求的內容類型。所以,我的問題是,有沒有辦法攔截這些請求並向它們添加內容類型?或者甚至有另一種解決方法?

回答

5

我認爲你可以使用ActionFilterAttribute。請參閱文檔:Creating Custom Action Filters。在你的情況下,你可以使用下面的示例(在C#中,因爲我的VB技能已經過時了)。它覆蓋任何請求Content-Type標頭的值爲application/json值。請注意,您可能需要對其進行增強才能支持各種HttpContent(例如,我認爲這不應該用於MultiPart請求)。

public class UpdateRequestAttribute: ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     actionContext.Request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); 
     base.OnActionExecuting(actionContext); 
    } 
} 

然後你這個屬性添加到您的控制器類,例如:

[UpdateRequest] 
public class HomeController : ApiController 
{ 
    //[...] 
} 

在這種情況下,給家庭控制器的所有請求都會有自己Content-Type覆蓋。


或者,您也可以編寫自定義HTTP Message Handlers這是在管道很早就打來電話,將不侷限於特定的控制器。檢查以下圖片以瞭解服務器如何處理請求。

ASP.net Server Side handlers

例如,該消息處理器將設置請求Content-Type應用/ JSON如果它是當前爲空。

public class CustomMessageHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     if (request.Content.Headers.ContentType == null) 
     { 
      request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); 
     } 
     return base.SendAsync(request, cancellationToken); 
    } 
} 

最後,這裏是如何以你的消息處理程序添加到管道更新WebApiConfig:通過定義路線attribute.This

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     config.MessageHandlers.Add(new CustomMessageHandler()); 

     // Other configuration not shown... 

    } 
} 
1

您可以同時在同一個控制器,這些方法您可以避免模型綁定屬性。

[Route("Request1")] 
Public Function POSTRequest(Action As String, Stamp As String) As HttpResponseMessage 
      ... 
     End Function 
     [Route("Request2")] 
     Public Function POSTRequest(Action As String, OpStamp As String) As HttpResponseMessage 
      ... 
     End Function 

不要忘記啓用屬性通過在webapiconfig.vb文件中添加MapHttpAttributeRoutes路由

Public Module WebApiConfig 
    Public Sub Register(ByVal config As HttpConfiguration) 
     ' Web API configuration and services 

     ' Web API routes 
     config.MapHttpAttributeRoutes() 

     config.Routes.MapHttpRoute(
      name:="DefaultApi", 
      routeTemplate:="api/{controller}/{id}", 
      defaults:=New With {.id = RouteParameter.Optional} 
     ) 
    End Sub 
End Module