自定义ActionResult始终为“ContentType”返回空字符串

时间:2011-10-03 14:38:25

标签: asp.net-mvc-3 content-type

我有以下自定义ActionResult。如果我“强制”ContentType,它可以正常工作,但默认行为似乎是检索空字符串作为ContentType

C#版

public ActionResult Restful(Web.Mvc.Controller controller)
{
    // Test code
    var contentType = controller.Request.ContentType;
    // Above always returns ""

    switch (ResultType(controller)) {
        case RestfulResultType.Html:
            ViewResult result = new ViewResult();
            return result;
        case RestfulResultType.Json:
            JsonResult result = new JsonResult();
            return result;
        case RestfulResultType.JsonP:
            JsonPResult result = new JsonPResult();
            return result;
        case RestfulResultType.Xml:
            return new XmlResult(null);
        default:
            ViewResult result = new ViewResult();
            return result;
    }

}

VB.NET版本

    <Extension()>
    Public Function Restful(controller As Web.Mvc.Controller) As ActionResult

    ''# Test code
    Dim contentType = controller.Request.ContentType
    ''# Above always returns ""

        Select Case ResultType(controller)
            Case RestfulResultType.Html
                Dim result As New ViewResult()
                Return result
            Case RestfulResultType.Json
                Dim result As New JsonResult()
                Return result
            Case RestfulResultType.JsonP
                Dim result As New JsonPResult()
                Return result
            Case RestfulResultType.Xml
                Return New XmlResult(Nothing)
            Case Else
                Dim result As New ViewResult()
                Return result
        End Select

    End Function

为什么我不能从中获取相应的contentType?

PS:如果你关心ResultType做了什么,就在这里。

    Private Function ResultType(controller As Web.Mvc.Controller) As RestfulResultType

        Select Case LCase(controller.HttpContext.Request.ContentType)
            Case "text/html" : Return RestfulResultType.Html
            Case "application/json" : Return RestfulResultType.Json
            Case "text/javascript" : Return RestfulResultType.JsonP
            Case "application/javascript" : Return RestfulResultType.JsonP
            Case "application/x-javascript" : Return RestfulResultType.JsonP
            Case "text/xml" : Return RestfulResultType.Xml
            Case "application/xml" : Return RestfulResultType.Xml
            Case Else : Return RestfulResultType.Html
        End Select
    End Function

1 个答案:

答案 0 :(得分:0)

Request.ContentType是

  

请求正文的mime类型(与POST和PUT请求一起使用

您应该检查HttpRequest.Accept标头值

  

可接受的内容类型