简体   繁体   中英

Calling AccountController Register web api method from a console application

I want to register a user from a console application. How can I add a user object to the web api call?

My approach thus far has been like this.

This is the account controller method

public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName };

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

        //*******************************
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }
        //check role and create




        return Ok("success");
    }

I want to call this from the Console application and add a user object.

static async Task Register(RegisterBindingModel user)
    {
        System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        client.BaseAddress = new Uri("http://localhost/MyService/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        var resp2 = client.PostAsync("api/Account/Register", //how would I add the user object)


    }

How would I go about in add the user object to my call?

Kind regards

You can convert your object to json using newtonsoft:

var myJson = JsonConvert.SerializeObject(myObj);

Then you create a new StringContent :

var content = new StringContent(myJson, Encoding.UTF8, "application/json");

See documentation StringContent constructor and StringContent

And then you pass this in:

await client.PostAsync("api/Account/Register", content)

Two objects you can pass through to the SerializeObject , you could do an anonymous type:

var myJson = JsonConvert.SerializeObject(new { firstName = "Bob", lastName = "Marley" });

Or, you could create model that looks exactly like the request object the controller is expecting:

class RegistrationModel
{
    public string FirstName {get;set;} // etc.. etc...
}

var myJson = JsonConvert.SerializeObject(new RegistrationModel { FirstName = "Bob" });

I actually create myself a JsonContent object to use instead:

public class JsonContent : StringContent
{
    private const string ApplicationJsonMediaType = "application/json";
    public JsonContent(object content) : base(SerializeContent(content), Encoding.UTF8, ApplicationJsonMediaType)
    {
    }

    private static string SerializeContent(object content)
    {
        return JsonConvert.SerializeObject(content);
    }
}

And use:

var content = new JsonContent(myObj);
await client.PostAsync("api/Account/Register", content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM