Asp.net mvc 如何将JSON发布到ASP.NET控制器操作?
如何将JSON发布到ASP.NET MVC控制器操作 示例场景Asp.net mvc 如何将JSON发布到ASP.NET控制器操作?,asp.net-mvc,json,post,Asp.net Mvc,Json,Post,如何将JSON发布到ASP.NET MVC控制器操作 示例场景 外部身份验证系统需要向其发布JSON。我想在我的站点上捕获用户的凭据,并将它们作为JSON转发到身份验证站点。重定向不是一个选项。因此我们将使用http://www.example.com/ExtAuth/Login作为我们虚构的外部身份验证端点 ExtAuth希望我们发布一个JSON字符串,该字符串表示一个具有两个属性的对象:User,和Password ExtAuth将返回一个JSON字符串,该字符串表示具有两个属性的对象:St
外部身份验证系统需要向其发布JSON。我想在我的站点上捕获用户的凭据,并将它们作为JSON转发到身份验证站点。重定向不是一个选项。因此我们将使用
http://www.example.com/ExtAuth/Login
作为我们虚构的外部身份验证端点
ExtAuth希望我们发布一个JSON字符串,该字符串表示一个具有两个属性的对象:User
,和Password
ExtAuth将返回一个JSON字符串,该字符串表示具有两个属性的对象:Status
,和Message
使整个过程正常运行的关键是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
作为ActionResult的公共函数登录(ByVal模型作为LoginModel)
Dim authEndpointUrl作为字符串=”http://www.example.com/ExtAuth/Login"
Dim result As String=String.Empty'这将保存从ExtAuth返回的JSON
Dim resultModel As LoginResult=Nothing'结果JSON的反序列化形式
Dim data As String=String.Empty'登录数据的序列化表示形式
Dim extRequest作为HttpWebRequest=WebRequest.CreateHttp(authEndpointUrl)
extRequest.Method=“POST”
extRequest.ContentType=“应用程序/json”
data=Newtonsoft.Json.JsonConvert.SerializeObject(模型)
将writer用作StreamWriter=newstreamwriter(extRequest.GetRequestStream)
writer.Write(数据)
终端使用
使用ExtraResponse作为HttpWebResponse=ExtraRequest.GetResponse
将读卡器用作StreamReader=新的StreamReader(extResponse.GetResponseStream)
结果=reader.ReadToEnd
终端使用
终端使用
resultModel=Newtonsoft.Json.JsonConvert.DeserializeObject(属于LoginResult)(结果)
ViewData(“状态”)=结果模型状态
ViewData(“消息”)=结果模型消息
返回视图(模型)
端函数
此方法应适用于MVC 3+。@andreCounts回答您自己的问题是不被禁止的: