如何从URL Aspnet WebApi读取字符串参数和表单数据

时间:2017-07-12 11:48:22

标签: c# asp.net-mvc asp.net-web-api

1 - 我从WebApi控制器生成链接,传递两个参数:

var URL = new Uri( Url.Link("Default", new { Controller = "Reset", Action = 
"ResetPassword",user = "AAAAA", hash = "HASHVALUE" }));

我明白了:

http://localhost:52494/Reset/ResetPassword?user=BBBBBBBB&hash=AAAAAAA

2 - 我还需要阅读这两个参数和表格。

所以我有一个控制器Reset,其中包含ResetPassword操作:

public ActionResult ResetPassword()
{
    return View();
}

[HttpPost]
public ActionResult ResetPassword(Models.ResetUserModel user)
{
   var HASH = Request["hash"];     
   var id = Request["user"];
   return View();
}

和cshtml文件:

enter image description here

如果我运行此页面并填写表单,我将能够阅读ResetUserModel,但如果它有一些参数,则该模型为空!

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

您似乎没有在操作中定义相关参数,因为您从 URI 传递了两个参数:

user = "AAAAA", hash = "HASHVALUE"

var URL = new Uri( Url.Link("Default", new { Controller = "Reset", Action = 
"ResetPassword",user = "AAAAA", hash = "HASHVALUE" }));

所以你必须根据 来定义你的行动:

[HttpGet]
public ActionResult ResetPassword(string user, string hash)
{
   var user = user;     
   var hash = hash;

   return View();
}

答案 1 :(得分:0)

而不是使用HttpPost尝试使用Get方法:

[HttpGet]
public ActionResult ResetPassword(string user, string hash)
{
   //populate the model with the user and hash values
   var model = new ResetUserModel();
   model.User = user;
   model.Hash = hash;
   return View(model);
}

您可以使用链接调用ResetPassword

http://localhost:52494/Reset/ResetPassword?user=BBBBBBBB&hash=AAAAAAA