Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ASP .NET MVC WebAPI 2 method properly

I have created separated project for ASP .NET MVC WebAPI 2 and I would like to call Register method. (I use a project is created by VS2013 by default.)

[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();
    }

I use a simple WPF app to do this. I am not sure about the syntax to call this method and pass username and password to it dueRegisterBindingModel.

  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
            {
            }
        } 

Any clue?

like image 510
Friend Avatar asked Jan 03 '14 12:01

Friend


People also ask

Can we have multiple get methods in Web API?

As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.

How do I fix the CORS issue in Web API?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.


2 Answers

It is depending from routing of yor Web API service but seems to be you have forgotten controller name in route.

By default it should be

api/Account/Register

Or your code

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...);

And by the way HTTP Verb should be POST and not GET and you should put something into the body.

You can pass through body using PostAsync method argument called Content. In your case the best choice will be use ObjectContent

Sample on how to use object you can find here Calling a Web API From a .NET Client, quote from this article:

PostAsJsonAsync is an extension method defined in System.Net.Http.HttpClientExtensions. It is equivalent to the following:

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;
like image 144
Regfor Avatar answered Sep 25 '22 15:09

Regfor


Basically you need to serialize the model into the post body in a way that the mvc framework can deserialize and form the model again. These posts should help you with the format of the serialized data:

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

like image 34
JTMon Avatar answered Sep 22 '22 15:09

JTMon