在asp.net Identity动作方法中传递HttpPostedFileBase对象并使用face api进行验证

时间:2017-11-03 21:11:25

标签: c# asp.net azure asp.net-identity

大家好,我尝试使用asp.net身份实现注册功能。

我需要的一个属性是新用户的照片,我在动作方法中作为参数传递,最后我调用了azure face api的faceServiceClient.DetectAsync()方法。

我在视图中使用<input type='file'>抓取照片 然后在注册操作方法中的身份控制器身份我使用HttpPostedFileBase object来阅读它。

问题是faceServiceClient.DetectAsync()需要第一个参数作为流对象或字符串(imagePath),但在我的情况下,我无法弄清楚如何给出流对象或图像路径

HttpPostedFileBase不检索图像路径,但要获取图像,我需要这种类型的对象。

然后,即使我尝试传递httpPostedFilebase object.InputStream作为参数,我也会通过指向await faceServiceClient.DetectAsync命令行的

获取null

具体

帐户控制器

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register([Bind(Exclude = "UserPhoto")]RegisterViewModel model, HttpPostedFileBase userPhoto)
    {
        if ((userPhoto==null) || (userPhoto.ContentLength <= 0))
        {
            ModelState.AddModelError("error", @"Please Select a profile picture");
        }

        if (ModelState.IsValid)
         {
          var faceApiresult = await new FaceRecognitionController().GetDetectedFaces(userPhoto);

          if (!faceApiresult)
          {
               ModelState.AddModelError("error", @"Your picture does not include your face");
                return RedirectToAction("Index", "Home");
            }



            var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email = model.Email,
                    UName = model.Username,
                    UserPhoto = model.UserPhoto
                };

                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");


                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);

        }


        // If we got this far, something failed, redisplay form
        return View(model);
    }

和我的 FaceRecognitionController

public class FaceRecognitionController : Controller
{

    private static string ServiceKey = ConfigurationManager.AppSettings["FaceServiceKey"];
    private static string EndPoint = ConfigurationManager.AppSettings["FaceServiceEndPoint"];

            [HttpGet]
            public  async Task<dynamic> GetDetectedFaces(HttpPostedFile userPhoto)
            {
              var photo = new byte[userPhoto.ContentLength];

              if (userPhoto.ContentLength == 0) return false;
                try
                {
                    // Create Instance of Service Client by passing Servicekey as parameter in constructor 
                    var faceServiceClient = new FaceServiceClient(ServiceKey);
                    var faces = await faceServiceClient.DetectAsync(userPhoto.InputStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses });
                    //check if find any faces
                    var results = faces.Length;


                    return results != 0;
                }
                catch (FaceAPIException)
                {
                    //do exception work
                }

                return false;
            }

           }
         }

正如您所看到的,我只是检查验证api是否找到任何面孔,然后返回true以完成注册

关于我如何克服这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

好了一些搜索后我发现了这篇文章

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

我读到我可以使用这行代码

var filePath = Path.GetTempFileName();

并获取临时文件路径。之后,我成功将其作为参数添加到操作方法,然后在faceServiceClient.DetectAsync中 并使用tis路径作为第一个参数并工作