如何正确调用ASP .NET MVC Web API 2方法

时间:2014-01-03 12:14:02

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

我为 ASP .NET MVC WebAPI 2 创建了单独的项目,我想调用Register方法。 (我使用的项目默认是由VS2013创建的。)

[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    .... 

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        IdentityUser user = new IdentityUser
        {
            UserName = model.UserName
        };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);
        IHttpActionResult errorResult = GetErrorResult(result);

        if (errorResult != null)
        {
            return errorResult;
        }

        return Ok();
    }

我使用简单的WPF应用来执行此操作。由于RegisterBindingModel,我不确定调用此方法并将用户名和密码传递给它的语法。

  public partial class MainWindow : Window
    {
        HttpClient client;

        public MainWindow()
        {
            InitializeComponent();        
        }

        private  void Button_Click(object sender, RoutedEventArgs e)
        {
            Test();
        }

        private async void Test()
        {
            try
            {
                var handler = new HttpClientHandler();
                handler.UseDefaultCredentials = true;
                handler.PreAuthenticate = true;
                handler.ClientCertificateOptions = ClientCertificateOption.Automatic;

                handler.Credentials = new NetworkCredential("test01","test01"); 

                client = new HttpClient(handler);
                client.BaseAddress = new Uri("http://localhost:22678/");
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json")); // It  tells the server to send data in JSON format.

                var response = await client.GetAsync("api/Register");
                response.EnsureSuccessStatusCode(); // Throw on error code.

                // How to pass RegisterBindingModel ???     
                var data = await response.Content.ReadAsAsync<?????>();

            }
            catch (Newtonsoft.Json.JsonException jEx)
            {
                MessageBox.Show(jEx.Message);
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
            }
        } 

有任何线索吗?

2 个答案:

答案 0 :(得分:6)

它取决于您的Web API服务的路由,但似乎您忘记了路由中的控制器名称。

默认情况下应为

api/Account/Register

或您的代码

client.BaseAddress = new Uri("http://localhost:22678/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
var response = await client.PostAsync("api/Account/Register", ...body content...);

顺便说一句HTTP Verb应该是POST而不是GET,你应该把东西放进身体。

您可以使用PostAsync method argument called Content传递身体。在您的情况下,最好的选择是使用ObjectContent

有关如何使用对象的示例,请参阅此处Calling a Web API From a .NET Client,引用本文:

  

PostAsJsonAsync是一个定义的扩展方法   System.Net.Http.HttpClientExtensions。它相当于   以下内容:

var product = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };

// Create the JSON formatter.
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

// Use the JSON formatter to create the content of the request body.
HttpContent content = new ObjectContent<Product>(product, jsonFormatter);

// Send the request.
var resp = client.PostAsync("api/products", content).Result;

答案 1 :(得分:1)

基本上,您需要将模型序列化到帖子正文中,以便mvc框架可以反序列化并再次形成模型。这些帖子应该可以帮助您了解序列化数据的格式:

http://www.asp.net/web-api/overview/formats-and-model-binding

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api