如何将JSON发布到ASP.NET控制器操作?

时间:2014-01-04 01:18:12

标签: asp.net-mvc json post

如何将JSON发布到ASP.NET MVC控制器操作?

示例场景

外部身份验证系统需要向其发布JSON。我想在我的网站上捕获用户的凭据,并将它们作为JSON转发到身份验证站点。重定向不是一种选择。

1 个答案:

答案 0 :(得分:0)

因此我们将http://www.example.com/ExtAuth/Login用作我们虚构的外部身份验证终结点。

ExtAuth希望我们发布一个JSON字符串,表示一个具有两个属性的对象:UserPassword

ExtAuth将返回一个JSON字符串,表示具有两个属性的对象:StatusMessage

使整个事情发挥作用的关键是 extRequest.ContentType 必须设置为 application/json

我会将正确的错误处理作为练习留给用户。

<HttpPost>
<AllowAnonymous>
Public Function Login(ByVal model As LoginModel) As ActionResult
  Dim authEndpointUrl As String = "http://www.example.com/ExtAuth/Login"
  Dim result As String = String.Empty  ' this will hold the JSON returned from ExtAuth
  Dim resultModel As LoginResult = Nothing  ' The deserialized form of the result JSON
  Dim data As String = String.Empty  ' the serialized representation of our login data

  Dim extRequest As HttpWebRequest = WebRequest.CreateHttp(authEndpointUrl)
      extRequest.Method = "POST"
      extRequest.ContentType = "application/json"

  data = Newtonsoft.Json.JsonConvert.SerializeObject(model)
  Using writer As StreamWriter = New StreamWriter(extRequest.GetRequestStream)
    writer.Write(data)
  End Using

  Using extResponse As HttpWebResponse = extRequest.GetResponse
    Using reader As StreamReader = New StreamReader(extResponse.GetResponseStream)
      result = reader.ReadToEnd
    End Using
  End Using

  resultModel = Newtonsoft.Json.JsonConvert.DeserializeObject(Of LoginResult)(result)
  ViewData("Status") = resultModel.Status
  ViewData("Message") = resultModel.Message

  Return View(model)

End Function

此方法适用于MVC 3 +。